system (original) (raw)
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.
proc &(x, y: char): string {.magic: "ConStrStr", noSideEffect, ...raises: [],
tags: [], forbids: [].}
Concatenates characters x and y into a string.
assert('a' & 'b' == "ab")
proc &(x, y: string): string {.magic: "ConStrStr", noSideEffect, ...raises: [],
tags: [], forbids: [].}
Concatenates strings x and y.
assert("ab" & "cd" == "abcd")
proc &(x: char; y: string): string {.magic: "ConStrStr", noSideEffect,
...raises: [], tags: [], forbids: [].}
Concatenates x with y.
assert('a' & "bc" == "abc")
proc &(x: string; y: char): string {.magic: "ConStrStr", noSideEffect,
...raises: [], tags: [], forbids: [].}
Concatenates x with y.
assert("ab" & 'c' == "abc")
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:
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:
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])
proc &=(x: var string; y: string) {.magic: "AppendStrStr", noSideEffect,
...raises: [], tags: [], forbids: [].}
Appends in place to a string.
var a = "abc" a &= "de"
proc *(x, y: float): float {.magic: "MulF64", noSideEffect, ...raises: [],
tags: [], forbids: [].}
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: [].}
proc *(x, y: int16): int16 {.magic: "MulI", noSideEffect, ...raises: [],
tags: [], forbids: [].}
proc *(x, y: int32): int32 {.magic: "MulI", noSideEffect, ...raises: [],
tags: [], forbids: [].}
proc *(x, y: int64): int64 {.magic: "MulI", noSideEffect, ...raises: [],
tags: [], forbids: [].}
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: [].}
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}
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.
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: [].}
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: [].}
proc +(x, y: int16): int16 {.magic: "AddI", noSideEffect, ...raises: [],
tags: [], forbids: [].}
proc +(x, y: int32): int32 {.magic: "AddI", noSideEffect, ...raises: [],
tags: [], forbids: [].}
proc +(x, y: int64): int64 {.magic: "AddI", noSideEffect, ...raises: [],
tags: [], forbids: [].}
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: [].}
proc +(x: float): float {.magic: "UnaryPlusF64", noSideEffect, ...raises: [],
tags: [], forbids: [].}
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: [].}
proc +(x: int16): int16 {.magic: "UnaryPlusI", noSideEffect, ...raises: [],
tags: [], forbids: [].}
proc +(x: int32): int32 {.magic: "UnaryPlusI", noSideEffect, ...raises: [],
tags: [], forbids: [].}
proc +(x: int64): int64 {.magic: "UnaryPlusI", noSideEffect, ...raises: [],
tags: [], forbids: [].}
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}
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.
proc +=[T: SomeInteger](x: var T; y: T) {.magic: "Inc", noSideEffect,
...raises: [], tags: [], forbids: [].}
Increments an integer.Source Edit
proc -(x, y: float): float {.magic: "SubF64", noSideEffect, ...raises: [],
tags: [], forbids: [].}
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: [].}
proc -(x, y: int16): int16 {.magic: "SubI", noSideEffect, ...raises: [],
tags: [], forbids: [].}
proc -(x, y: int32): int32 {.magic: "SubI", noSideEffect, ...raises: [],
tags: [], forbids: [].}
proc -(x, y: int64): int64 {.magic: "SubI", noSideEffect, ...raises: [],
tags: [], forbids: [].}
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: [].}
proc -(x: float): float {.magic: "UnaryMinusF64", noSideEffect, ...raises: [],
tags: [], forbids: [].}
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: [].}
proc -(x: int16): int16 {.magic: "UnaryMinusI", noSideEffect, ...raises: [],
tags: [], forbids: [].}
proc -(x: int32): int32 {.magic: "UnaryMinusI", noSideEffect, ...raises: [],
tags: [], forbids: [].}
proc -(x: int64): int64 {.magic: "UnaryMinusI64", noSideEffect, ...raises: [],
tags: [], forbids: [].}
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}
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.
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]
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]
proc /(x, y: float): float {.magic: "DivF64", noSideEffect, ...raises: [],
tags: [], forbids: [].}
proc /(x, y: int): float {.inline, noSideEffect, ...raises: [], tags: [],
forbids: [].}
Division of integers that results in a float.
echo 7 / 5
See also:
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.
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: [].}
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)
proc <(x, y: float): bool {.magic: "LtF64", noSideEffect, ...raises: [],
tags: [], forbids: [].}
proc <(x, y: float32): bool {.magic: "LtF64", noSideEffect, ...raises: [],
tags: [], forbids: [].}
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: [].}
proc <(x, y: int16): bool {.magic: "LtI", noSideEffect, ...raises: [], tags: [],
forbids: [].}
proc <(x, y: int32): bool {.magic: "LtI", noSideEffect, ...raises: [], tags: [],
forbids: [].}
proc <(x, y: int64): bool {.magic: "LtI", noSideEffect, ...raises: [], tags: [],
forbids: [].}
proc <(x, y: pointer): bool {.magic: "LtPtr", noSideEffect, ...raises: [],
tags: [], forbids: [].}
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)
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: [].}
proc <(x, y: uint16): bool {.magic: "LtU", noSideEffect, ...raises: [], tags: [],
forbids: [].}
proc <(x, y: uint32): bool {.magic: "LtU", noSideEffect, ...raises: [], tags: [],
forbids: [].}
proc <(x, y: uint64): bool {.magic: "LtU", noSideEffect, ...raises: [], tags: [],
forbids: [].}
proc <[Enum: enum](x, y: Enum): bool {.magic: "LtEnum", noSideEffect,
...raises: [], tags: [], forbids: [].}
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: [].}
proc <[T](x, y: ref T): bool {.magic: "LtPtr", noSideEffect, ...raises: [],
tags: [], forbids: [].}
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)
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: bool): bool {.magic: "LeB", noSideEffect, ...raises: [], tags: [],
forbids: [].}
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)
proc <=(x, y: float): bool {.magic: "LeF64", noSideEffect, ...raises: [],
tags: [], forbids: [].}
proc <=(x, y: float32): bool {.magic: "LeF64", noSideEffect, ...raises: [],
tags: [], forbids: [].}
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: [].}
proc <=(x, y: int16): bool {.magic: "LeI", noSideEffect, ...raises: [], tags: [],
forbids: [].}
proc <=(x, y: int32): bool {.magic: "LeI", noSideEffect, ...raises: [], tags: [],
forbids: [].}
proc <=(x, y: int64): bool {.magic: "LeI", noSideEffect, ...raises: [], tags: [],
forbids: [].}
proc <=(x, y: pointer): bool {.magic: "LePtr", noSideEffect, ...raises: [],
tags: [], forbids: [].}
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)
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: [].}
proc <=(x, y: uint16): bool {.magic: "LeU", noSideEffect, ...raises: [],
tags: [], forbids: [].}
proc <=(x, y: uint32): bool {.magic: "LeU", noSideEffect, ...raises: [],
tags: [], forbids: [].}
proc <=(x, y: uint64): bool {.magic: "LeU", noSideEffect, ...raises: [],
tags: [], forbids: [].}
proc <=[Enum: enum](x, y: Enum): bool {.magic: "LeEnum", noSideEffect,
...raises: [], tags: [], forbids: [].}
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: [].}
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)
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 =[T](dest: var T; src: T) {.noSideEffect, magic: "Asgn", ...raises: [],
tags: [], forbids: [].}
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: [].}
proc ==(x, y: float32): bool {.magic: "EqF64", noSideEffect, ...raises: [],
tags: [], forbids: [].}
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: [].}
proc ==(x, y: int16): bool {.magic: "EqI", noSideEffect, ...raises: [], tags: [],
forbids: [].}
proc ==(x, y: int32): bool {.magic: "EqI", noSideEffect, ...raises: [], tags: [],
forbids: [].}
proc ==(x, y: int64): bool {.magic: "EqI", noSideEffect, ...raises: [], tags: [],
forbids: [].}
proc ==(x, y: pointer): bool {.magic: "EqRef", noSideEffect, ...raises: [],
tags: [], forbids: [].}
Checks for equality between two pointer variables.
Example:
var a = castpointer b = castpointer assert a == b
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: [].}
proc ==(x, y: uint16): bool {.magic: "EqI", noSideEffect, ...raises: [],
tags: [], forbids: [].}
proc ==(x, y: uint32): bool {.magic: "EqI", noSideEffect, ...raises: [],
tags: [], forbids: [].}
proc ==(x, y: uint64): bool {.magic: "EqI", noSideEffect, ...raises: [],
tags: [], forbids: [].}
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)
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: 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}
proc =copy[T](dest: var T; src: T) {.noSideEffect, magic: "Asgn", ...raises: [],
tags: [], forbids: [].}
proc =destroy(x: string) {.inline, magic: "Destroy", enforceNoRaises,
...raises: [], tags: [], forbids: [].}
proc =destroy[T](x: ref T) {.inline, magic: "Destroy", ...raises: [], tags: [],
forbids: [].}
proc =destroy[T](x: seq[T]) {.inline, magic: "Destroy", ...raises: [], tags: [],
forbids: [].}
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 echo @b
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.
proc [][I: Ordinal; T](a: T; i: I): T {.noSideEffect, magic: "ArrGet",
...raises: [], tags: [], forbids: [].}
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:
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"
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:
proc []=[I: Ordinal; T, S](a: T; i: I; x: sink S) {.noSideEffect,
magic: "ArrPut", ...raises: [], tags: [], forbids: [].}
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]
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"
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"
func abs(x: int): int {.magic: "AbsI", inline, ...raises: [], tags: [], forbids: [].}
func abs(x: int8): int8 {.magic: "AbsI", inline, ...raises: [], tags: [], forbids: [].}
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).
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")
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")
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"
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"
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"]
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.
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!
proc addQuitProc(quitProc: proc () {.noconv.}) {.importc: "atexit", header: "<stdlib.h>", ...deprecated: "use exitprocs.addExitProc", raises: [], tags: [], forbids: [].}
Deprecated: use exitprocs.addExitProc
Adds/registers a quit procedure.
Each call to addQuitProc registers another quit procedure. Up to 30 procedures can be registered. They are executed on a last-in, first-out basis (that is, the last function registered is the first to be executed). addQuitProc raises an EOutOfIndex exception if quitProc cannot be registered.
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'""")
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 echo p[]
proc alignof[T](x: T): int {.magic: "AlignOf", noSideEffect, ...raises: [], tags: [], forbids: [].}
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 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.
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
proc and(x, y: int8): int8 {.magic: "BitandI", noSideEffect, ...raises: [],
tags: [], forbids: [].}
proc and(x, y: int16): int16 {.magic: "BitandI", noSideEffect, ...raises: [],
tags: [], forbids: [].}
proc and(x, y: int32): int32 {.magic: "BitandI", noSideEffect, ...raises: [],
tags: [], forbids: [].}
proc and(x, y: int64): int64 {.magic: "BitandI", noSideEffect, ...raises: [],
tags: [], forbids: [].}
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: [].}
proc arrayWith[T](y: T; size: static int): array[size, T] {.noinit, nodestroy, ...raises: [].}
Creates a new array filled with y.Source Edit
proc arrayWithDefault[T](size: static int): array[size, T] {.noinit, nodestroy, ...raises: [].}
Creates a new array filled with default(T).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
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
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
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
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)
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))
proc close[TMsg](c: var Channel[TMsg])
Closes a channel c and frees its associated resources.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!
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])
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.
proc compileOption(option, arg: string): bool {.magic: "CompileOptionArg", noSideEffect, ...raises: [], tags: [], forbids: [].}
Can be used to determine an enum compile-time option.
See also:
- compileOption for on|off options
- defined
- std/compilesettings module
Example:
when compileOption("opt", "size") and compileOption("gc", "boehm"): discard "compiled with optimization for size and uses Boehm's GC"
proc compileOption(option: string): bool {.magic: "CompileOption", noSideEffect, ...raises: [], tags: [], forbids: [].}
Can be used to determine an on|off compile-time option.
See also:
- compileOption for enum options
- defined
- std/compilesettings module
Example: cmd: --floatChecks:off
static: doAssert not compileOption("floatchecks") {.push floatChecks: on.} static: doAssert compileOption("floatchecks")
{.pop.}
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"
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
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)
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.
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:
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 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.
proc deallocImpl(p: pointer) {.noconv, ...gcsafe, tags: [], gcsafe, raises: [], forbids: [].}
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
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):
See also:
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: out 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.
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
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):
See also:
- compileOption for on|off options
- compileOption for enum options
- define pragmas 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]
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]
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
proc div(x, y: int8): int8 {.magic: "DivI", noSideEffect, ...raises: [],
tags: [], forbids: [].}
proc div(x, y: int16): int16 {.magic: "DivI", noSideEffect, ...raises: [],
tags: [], forbids: [].}
proc div(x, y: int32): int32 {.magic: "DivI", noSideEffect, ...raises: [],
tags: [], forbids: [].}
proc div(x, y: int64): int64 {.magic: "DivI", noSideEffect, ...raises: [],
tags: [], forbids: [].}
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: [].}
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 ,soitworksforuser−definedtypesthathaveanoverloaded, so it works for user-defined types that have an overloaded ,soitworksforuser−definedtypesthathaveanoverloaded 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.
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()
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.
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}
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 GC_disableMarkAndSweep() {....raises: [], raises: [], tags: [], forbids: [].}
For --mm:orc an alias for GC_disableOrc.Source Edit
proc GC_disableOrc() {....raises: [], 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: [], raises: [], tags: [], forbids: [].}
For --mm:orc an alias for GC_enableOrc.Source Edit
proc GC_enableOrc() {....raises: [], 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: [], raises: [], 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_partialCollect(limit: int) {....raises: [], raises: [], tags: [RootEffect], forbids: [].}
proc GC_prepareOrc(): int {.inline, ...raises: [], raises: [], tags: [], forbids: [].}
proc GC_ref[T](x: ref T) {....raises: [].}
New runtime only supports this operation for 'ref T'.Source Edit
proc GC_runOrc() {....raises: [], raises: [], tags: [RootEffect], forbids: [].}
Forces a cycle collection pass.Source Edit
proc GC_unref[T](x: ref T) {....raises: [].}
New runtime only supports this operation for 'ref T'.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: [].}
proc getFrameState(): FrameState {.compilerproc, inline, ...raises: [], tags: [], forbids: [].}
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 getOccupiedMem(): int {....gcsafe, raises: [], tags: [], forbids: [].}
Returns the number of bytes that are owned by the process and hold data.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 getThreadId(): int {....raises: [], 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 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.
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] {.noinit, ...raises: [], tags: [], forbids: [].}
Similar to gorge but also returns the precious exit code.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:
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)
See also:
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) for i in low(arr)..high(arr): echo arr[i]
See also:
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])
See also:
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)
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)
See also:
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) for i in low(s)..high(s): echo s[i]
See also:
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
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}
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)
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)
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:1: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))
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(testint == 3) assert(teststring == 0)
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: [].}
proc isNil[T](x: ref T): bool {.noSideEffect, magic: "IsNil", ...raises: [], tags: [], forbids: [].}
proc isUniqueRef[T](x: ref T): bool {.inline, ...raises: [].}
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
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
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 doAssert len(cstring"ab\0c") == 5 var a: cstring = "ab\0c" when defined(js): doAssert a.len == 4 else: doAssert a.len == 2 static: var a2: cstring = "ab\0c" doAssert a2.len == 2
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
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 newSeqint.len == 3 let s = newSeqOfCapint assert s.len == 0
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
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)
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
proc low(x: cstring): int {.magic: "Low", noSideEffect, ...raises: [], tags: [], forbids: [].}
Returns the lowest possible index of a compatible string x.
See also:
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)
See also:
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) for i in low(arr)..high(arr): echo arr[i]
See also:
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])
See also:
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)
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)
See also:
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) for i in low(s)..high(s): echo s[i]
See also:
proc max(x, y: int): int {.magic: "MaxI", noSideEffect, ...raises: [], tags: [], forbids: [].}
proc max(x, y: int8): int8 {.magic: "MaxI", noSideEffect, ...raises: [], tags: [], forbids: [].}
proc max(x, y: int16): int16 {.magic: "MaxI", noSideEffect, ...raises: [], tags: [], forbids: [].}
proc max(x, y: int32): int32 {.magic: "MaxI", noSideEffect, ...raises: [], tags: [], forbids: [].}
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 min(x, y: int): int {.magic: "MinI", noSideEffect, ...raises: [], tags: [], forbids: [].}
proc min(x, y: int8): int8 {.magic: "MinI", noSideEffect, ...raises: [], tags: [], forbids: [].}
proc min(x, y: int16): int16 {.magic: "MinI", noSideEffect, ...raises: [], tags: [], forbids: [].}
proc min(x, y: int32): int32 {.magic: "MinI", noSideEffect, ...raises: [], tags: [], forbids: [].}
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 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
proc mod(x, y: int8): int8 {.magic: "ModI", noSideEffect, ...raises: [],
tags: [], forbids: [].}
proc mod(x, y: int16): int16 {.magic: "ModI", noSideEffect, ...raises: [],
tags: [], forbids: [].}
proc mod(x, y: int32): int32 {.magic: "ModI", noSideEffect, ...raises: [],
tags: [], forbids: [].}
proc mod(x, y: int64): int64 {.magic: "ModI", noSideEffect, ...raises: [],
tags: [], forbids: [].}
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: [].}
proc move[T](x: var T): T {.magic: "Move", noSideEffect, ...raises: [], tags: [], forbids: [].}
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.
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.
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
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!
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 = newSeqstring assert len(inputStrings) == 3 inputStrings[0] = "The fourth" inputStrings[1] = "assignment" inputStrings[2] = "would crash"
See also:
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"
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 = newSeqOfCapint assert len(x) == 0 x.add(10) assert len(x) == 1
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 = newSeqUninitint assert len(x) == 3 x[0] = 10
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 = newSeqUninitializedint assert len(x) == 3 x[0] = 10
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.
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.
proc newStringUninit(len: Natural): string {.noSideEffect, ...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.
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
proc not(x: int8): int8 {.magic: "BitnotI", noSideEffect, ...raises: [],
tags: [], forbids: [].}
proc not(x: int16): int16 {.magic: "BitnotI", noSideEffect, ...raises: [],
tags: [], forbids: [].}
proc not(x: int32): int32 {.magic: "BitnotI", noSideEffect, ...raises: [],
tags: [], forbids: [].}
proc not(x: int64): int64 {.magic: "BitnotI", noSideEffect, ...raises: [],
tags: [], forbids: [].}
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: [].}
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() doAssert base of Base doAssert base of Sub1 doAssert base isnot Sub1 doAssert not (base of Sub2)
base = Sub2() doAssert base of Sub2 doAssert Sub2(base) != nil doAssertRaises(ObjectConversionDefect): discard Sub1(base)
var sub1 = Sub1() doAssert sub1 of Base doAssert sub1.Base of Sub1
doAssert not compiles(base of Unrelated)
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.
proc open[TMsg](c: var Channel[TMsg]; maxItems: int = 0)
Opens a channel c for inter thread communication.
The send operation will block until number of unprocessed items is less than maxItems.
For unlimited queue set maxItems to 0.
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.
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
proc or(x, y: int8): int8 {.magic: "BitorI", noSideEffect, ...raises: [],
tags: [], forbids: [].}
proc or(x, y: int16): int16 {.magic: "BitorI", noSideEffect, ...raises: [],
tags: [], forbids: [].}
proc or(x, y: int32): int32 {.magic: "BitorI", noSideEffect, ...raises: [],
tags: [], forbids: [].}
proc or(x, y: int64): int64 {.magic: "BitorI", noSideEffect, ...raises: [],
tags: [], forbids: [].}
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: [].}
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
proc peek[TMsg](c: var Channel[TMsg]): int
Returns the current number of messages in the channel c.
Returns -1 if the channel has been closed.
Note: This is dangerous to use as it encourages races. It's much better to use tryRecv proc instead.
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]
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
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.
procCall someMethod(a, b)
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.
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 = castproc(y: int): int {.nimcall.} echo c2(2) else: let c3 = castproc(y: int; env: pointer): int {.nimcall.} echo c3(3, e)
proc ready[TMsg](c: var Channel[TMsg]): bool
Returns true if some thread is waiting on the channel c for new messages.Source Edit
proc recv[TMsg](c: var Channel[TMsg]): TMsg
Receives a message from the channel c.
This blocks until a message has arrived! You may use peek proc to avoid the blocking.
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"
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.
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 fileexamplesfile_examplesfileexamplesi.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 =
runnableExamples:
const exported* = 123
assert timesTwo(5) == 10
block:
defer: echo "done"runnableExamples "-d:foo -b:cpp": import std/compilesettings assert querySetting(backend) == "cpp" assert defined(foo) runnableExamples "-r:off": import std/browsers openDefaultBrowser "https://forum.nim-lang.org/" 2 * x
proc send[TMsg](c: var Channel[TMsg]; msg: sink TMsg) {.inline.}
Sends a message to a thread. msg is deeply copied.Source Edit
proc setControlCHook(hook: proc () {.noconv.}) {....raises: [], gcsafe, tags: [], forbids: [].}
Allows you to override the behaviour of your application when CTRL+C is pressed. Only one such hook is supported.
The handler runs inside a C signal handler and comes with similar limitations.
Allocating memory and interacting with most system calls, including using echo, string, seq, raising or catching exceptions etc is undefined behavior and will likely lead to application crashes.
The OS may call the ctrl-c handler from any thread, including threads that were not created by Nim, such as happens on Windows.
Example:
var stop: Atomic[bool] proc ctrlc() {.noconv.} =
stop.store(true)setControlCHook(ctrlc)
while not stop.load(): echo "Still running.." sleep(1000)
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.
proc setFrame(s: PFrame) {.compilerproc, inline, ...raises: [], tags: [], forbids: [].}
proc setFrameState(state: FrameState) {.compilerproc, inline, ...raises: [], tags: [], forbids: [].}
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) echo myS, " is fantastic!!"
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]
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]
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
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: 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:
- ashr func for arithmetic shift right
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
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 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)
proc slurp(filename: string): string {.magic: "Slurp", ...raises: [], tags: [], forbids: [].}
This is an alias for staticRead.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")
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.
proc substr(a: openArray[char]): string {....raises: [], tags: [], forbids: [].}
Returns a new string, copying contents of a.
**Warning:**As opposed to other
substr
overloads, no additional input validation and clamping is performed!
This proc does not prevent raising an IndexDefect when a is being passed using a toOpenArray call with out-of-bounds indexes:
- doAssertRaises(IndexDefect): discard "abc".toOpenArray(-9, 9).substr()
If clamping is required, consider using substr(s: string; first, last: int):
- doAssert "abc".substr(-9, 9) == "abc"
Example:
let a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
assert a.substr() == "abcdefgh"
assert a.toOpenArray(2, 5).substr() == "cdef"
assert a.toOpenArray(2, high(a)).substr() == "cdefgh"
doAssertRaises(IndexDefect): discard a.toOpenArray(5, 99).substr()
proc substr(s: string; first = 0): string {....raises: [], tags: [], forbids: [].}
Convenience substr overload that returns a substring from first to the end of the string.
first value is validated and capped:
- first >= s.len returns an empty string
- Negative first is clamped to 0.
Example:
let a = "abcdefgh"
assert a.substr(2) == "cdefgh"
assert a.substr(100) == ""
assert a.substr(-1) == "abcdefgh"
proc substr(s: string; first, last: int): string {....raises: [], tags: [], forbids: [].}
Returns a new string containing a substring (slice) of s, copying characters from index first to index last inclusive.
Index values are validated and capped:
- Negative first is clamped to 0
- If last >= s.len, it is clamped to high(s)
- If last < first, returns an empty string
This means substr can also be used to cut or limit a string's length.
**Note:**If index values are ensured to be in-bounds, for performance critical cases consider using a non-clamping overload substr(a: openArray[char])
Example:
let a = "abcdefgh" assert a.substr(2, 5) == "cdef"
assert a.substr(5, 99) == "fgh"
assert a.substr(42, 99) == ""
assert a.substr(100, 5) == ""
assert a.substr(-1, 2) == "abc"
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
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
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
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
proc toOpenArray[I, T](x: array[I, T]; first, last: I): openArray[T] {. magic: "Slice", ...raises: [], tags: [], forbids: [].}
proc toOpenArray[T](x: seq[T]; first, last: int): openArray[T] {.magic: "Slice", ...raises: [], tags: [], forbids: [].}
Returns a non-owning slice (a view) of x from the element at index first to last inclusive. Allows passing slices without copying, as opposed to using the slice operator [`[]`](#[],openArray[T],HSlice[U: Ordinal,V: Ordinal]).
Example:
proc test(x: openArray[int]) = doAssert x == [1, 2, 3]
let s = @[0, 1, 2, 3, 4] s.toOpenArray(1, 3).test
proc tryRecv[TMsg](c: var Channel[TMsg]): tuple[dataAvailable: bool, msg: TMsg]
Tries to receive a message from the channel c, but this can fail for all sort of reasons, including contention.
If it fails, it returns (false, default(msg)) otherwise it returns (true, msg).
proc trySend[TMsg](c: var Channel[TMsg]; msg: sink TMsg): bool {.inline.}
Tries to send a message to a thread.
msg is deeply copied. Doesn't block.
Returns false if the message was not sent because number of pending items in the channel exceeded maxItems.
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))
proc unsafeAddr[T](x: T): ptr T {.magic: "Addr", noSideEffect, ...raises: [], tags: [], forbids: [].}
Warning:
unsafeAddr
is a deprecated alias for
addr
, use
addr
instead.
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:
proc unsetControlCHook() {....raises: [], tags: [], forbids: [].}
Reverts a call to setControlCHook.Source Edit
proc wasMoved[T](obj: var T) {.magic: "WasMoved", noSideEffect, ...raises: [], tags: [], forbids: [].}
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 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
proc xor(x, y: int8): int8 {.magic: "BitxorI", noSideEffect, ...raises: [],
tags: [], forbids: [].}
proc xor(x, y: int16): int16 {.magic: "BitxorI", noSideEffect, ...raises: [],
tags: [], forbids: [].}
proc xor(x, y: int32): int32 {.magic: "BitxorI", noSideEffect, ...raises: [],
tags: [], forbids: [].}
proc xor(x, y: int64): int64 {.magic: "BitxorI", noSideEffect, ...raises: [],
tags: [], forbids: [].}
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: [].}
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:
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.