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

ProcUsageAlso 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

Channel support for threads.

Note: This is part of the system module. Do not import it directly. To activate thread support compile with the --threads:on command line switch.

Note: Channels are designed for the Thread type. They are unstable when used with spawn

Note: The current implementation of message passing does not work with cyclic data structures.

Note: Channels cannot be passed between threads. Use globals or pass them by ptr.

Example

The following is a simple example of two different ways to use channels: blocking and non-blocking.

  1. # Be sure to compile with --threads:on.
  2. # The channels and threads modules are part of system and should not be
  3. # imported.
  4. import std/os
  5. # Channels can either be:
  6. # - declared at the module level, or
  7. # - passed to procedures by ptr (raw pointer) -- see note on safety.
  8. #
  9. # For simplicity, in this example a channel is declared at module scope.
  10. # Channels are generic, and they include support for passing objects between
  11. # threads.
  12. # Note that objects passed through channels will be deeply copied.
  13. var chan: Channel[string]
  14. # This proc will be run in another thread using the threads module.
  15. proc firstWorker() =
  16. chan.send("Hello World!")
  17. # This is another proc to run in a background thread. This proc takes a while
  18. # to send the message since it sleeps for 2 seconds (or 2000 milliseconds).
  19. proc secondWorker() =
  20. sleep(2000)
  21. chan.send("Another message")
  22. # Initialize the channel.
  23. chan.open()
  24. # Launch the worker.
  25. var worker1: Thread[void]
  26. createThread(worker1, firstWorker)
  27. # Block until the message arrives, then print it out.
  28. echo chan.recv() # "Hello World!"
  29. # Wait for the thread to exit before moving on to the next example.
  30. worker1.joinThread()
  31. # Launch the other worker.
  32. var worker2: Thread[void]
  33. createThread(worker2, secondWorker)
  34. # This time, use a non-blocking approach with tryRecv.
  35. # Since the main thread is not blocked, it could be used to perform other
  36. # useful work while it waits for data to arrive on the channel.
  37. while true:
  38. let tried = chan.tryRecv()
  39. if tried.dataAvailable:
  40. echo tried.msg # "Another message"
  41. break
  42. echo "Pretend I'm doing useful work..."
  43. # For this example, sleep in order not to flood stdout with the above
  44. # message.
  45. sleep(400)
  46. # Wait for the second thread to exit before cleaning up the channel.
  47. worker2.joinThread()
  48. # Clean up the channel.
  49. chan.close()

Sample output

The program should output something similar to this, but keep in mind that exact results may vary in the real world:

  1. Hello World!
  2. Pretend I'm doing useful work...
  3. Pretend I'm doing useful work...
  4. Pretend I'm doing useful work...
  5. Pretend I'm doing useful work...
  6. Pretend I'm doing useful work...
  7. Another message

Passing Channels Safely

Note that when passing objects to procedures on another thread by pointer (for example through a thread’s argument), objects created using the default allocator will use thread-local, GC-managed memory. Thus it is generally safer to store channel objects in global variables (as in the above example), in which case they will use a process-wide (thread-safe) shared heap.

However, it is possible to manually allocate shared memory for channels using e.g. system.allocShared0 and pass these pointers through thread arguments:

  1. proc worker(channel: ptr Channel[string]) =
  2. let greeting = channel[].recv()
  3. echo greeting
  4. proc localChannelExample() =
  5. # Use allocShared0 to allocate some shared-heap memory and zero it.
  6. # The usual warnings about dealing with raw pointers apply. Exercise caution.
  7. var channel = cast[ptr Channel[string]](
  8. allocShared0(sizeof(Channel[string]))
  9. )
  10. channel[].open()
  11. # Create a thread which will receive the channel as an argument.
  12. var thread: Thread[ptr Channel[string]]
  13. createThread(thread, worker, channel)
  14. channel[].send("Hello from the main thread!")
  15. # Clean up resources.
  16. thread.joinThread()
  17. channel[].close()
  18. deallocShared(channel)
  19. localChannelExample() # "Hello from the main thread!"

Imports

exceptions, since, ctypes, ctypes, sysatomics, ansi_c, memory, syslocks, threadtypes, assertions, iterators, coro_detection, dollars, typedthreads, miscdollars, stacktraces, countbits_impl, syslocks, sysatomics, sharedlist, digitsutils, syslocks, digitsutils, widestrs, syncio

Types

  1. AllocStats = object

Source Edit

  1. 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

  1. array[I; T] {.magic: "Array".}

Generic type to construct fixed-length arrays. Source Edit

  1. auto {.magic: Expr.}

Meta type for automatic type determination. Source Edit

  1. BackwardsIndex = distinct int

Type that is constructed by ^ for reversed array accesses. (See ^ template) Source Edit

  1. bool {.magic: "Bool".} = enum
  2. false = 0, true = 1

Built-in boolean type. Source Edit

  1. byte = uint8

This is an alias for uint8, that is an unsigned integer, 8 bits wide. Source Edit

  1. CatchableError = object of Exception

Abstract class for all exceptions that are catchable. Source Edit

  1. Channel[TMsg] {....gcsafe.} = RawChannel

a channel for thread communication Source Edit

  1. char {.magic: Char.}

Built-in 8 bit character type (unsigned). Source Edit

  1. csize {.importc: "size_t", nodecl, ...deprecated: "use `csize_t` instead".} = int

Deprecated: use `csize_t` instead

This isn’t the same as size_t in C. Don’t use it. Source Edit

  1. cstring {.magic: Cstring.}

Built-in cstring (compatible string) type. Source Edit

  1. 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

  1. Endianness = enum
  2. littleEndian, bigEndian

Type describing the endianness of a processor. Source Edit

  1. Exception {.compilerproc, magic: "Exception".} = object of RootObj
  2. parent*: ref Exception ## Parent exception (can be used as a stack).
  3. name*: cstring ## The exception's name is its Nim identifier.
  4. ## This field is filled automatically in the
  5. ## `raise` statement.
  6. msg* {.exportc: "message".}: string ## The exception's message. Not
  7. ## providing an exception message
  8. ## is bad style.
  9. when defined(js):
  10. trace*: string
  11. else:
  12. trace*: seq[StackTraceEntry]

Base exception class.

Each exception has to inherit from Exception. See the full exception hierarchy.

Source Edit

  1. float {.magic: Float.}

Default floating point type. Source Edit

  1. float32 {.magic: Float32.}

32 bit floating point type. Source Edit

  1. float64 {.magic: Float.}

64 bit floating point type. Source Edit

  1. ForeignCell = object
  2. data*: pointer

Source Edit

  1. ForLoopStmt {.compilerproc.} = object

A special type that marks a macro as a for-loop macro. See “For Loop Macro”. Source Edit

  1. GC_Strategy = enum
  2. gcThroughput, ## optimize for throughput
  3. gcResponsiveness, ## optimize for responsiveness (default)
  4. gcOptimizeTime, ## optimize for speed
  5. gcOptimizeSpace ## optimize for memory footprint

The strategy the GC should use for the application. Source Edit

  1. HSlice[T; U] = object
  2. a*: T ## The lower bound (inclusive).
  3. b*: U ## The upper bound (inclusive).

“Heterogeneous” slice type. Source Edit

  1. int {.magic: Int.}

Default integer type; bitwidth depends on architecture, but is always the same as a pointer. Source Edit

  1. int8 {.magic: Int8.}

Signed 8 bit integer type. Source Edit

  1. int16 {.magic: Int16.}

Signed 16 bit integer type. Source Edit

  1. int32 {.magic: Int32.}

Signed 32 bit integer type. Source Edit

  1. int64 {.magic: Int64.}

Signed 64 bit integer type. Source Edit

  1. iterable[T] {.magic: IterableType.}

Represents an expression that yields T Source Edit

  1. JsRoot = ref object of RootObj

Root type of the JavaScript object hierarchy Source Edit

  1. lent[T] {.magic: "BuiltinType".}

Source Edit

  1. 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

  1. NimNode {.magic: "PNimrodNode".} = ref NimNodeObj

Represents a Nim AST node. Macros operate on this type. Source Edit

  1. 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

  1. Ordinal[T] {.magic: Ordinal.}

Generic ordinal type. Includes integer, bool, character, and enumeration types as well as their subtypes. See also SomeOrdinal. Source Edit

  1. owned[T] {.magic: "BuiltinType".}

type constructor to mark a ref/ptr or a closure as owned. Source Edit

  1. PFrame = ptr TFrame

Represents a runtime frame of the call stack; part of the debugger API. Source Edit

  1. pointer {.magic: Pointer.}

Built-in pointer type, use the addr operator to get a pointer to a variable. Source Edit

  1. 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

  1. ptr[T] {.magic: Pointer.}

Built-in generic untraced pointer type. Source Edit

  1. range[T] {.magic: "Range".}

Generic type to construct range types. Source Edit

  1. ref[T] {.magic: Pointer.}

Built-in generic traced pointer type. Source Edit

  1. RootEffect {.compilerproc.} = object of RootObj

Base effect class.

Each effect should inherit from RootEffect unless you know what you’re doing.

Source Edit

  1. 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

  1. RootRef = ref RootObj

Reference to RootObj. Source Edit

  1. seq[T] {.magic: "Seq".}

Generic type to construct sequences. Source Edit

  1. set[T] {.magic: "Set".}

Generic type to construct bit sets. Source Edit

  1. sink[T] {.magic: "BuiltinType".}

Source Edit

  1. Slice[T] = HSlice[T, T]

An alias for HSlice[T, T]. Source Edit

  1. SomeFloat = float | float32 | float64

Type class matching all floating point number types. Source Edit

  1. SomeInteger = SomeSignedInt | SomeUnsignedInt

Type class matching all integer types. Source Edit

  1. SomeNumber = SomeInteger | SomeFloat

Type class matching all number types. Source Edit

  1. SomeOrdinal = int | int8 | int16 | int32 | int64 | bool | enum | uint | uint8 |
  2. uint16 |
  3. uint32 |
  4. uint64

Type class matching all ordinal types; however this includes enums with holes. See also Ordinal Source Edit

  1. SomeSignedInt = int | int8 | int16 | int32 | int64

Type class matching all signed integer types. Source Edit

  1. SomeUnsignedInt = uint | uint8 | uint16 | uint32 | uint64

Type class matching all unsigned integer types. Source Edit

  1. StackTraceEntry = object
  2. procname*: cstring ## Name of the proc that is currently executing.
  3. line*: int ## Line number of the proc that is currently executing.
  4. filename*: cstring ## Filename of the proc that is currently executing.
  5. when NimStackTraceMsgs:
  6. frameMsg*: string ## When a stacktrace is generated in a given frame and
  7. ## rendered at a later time, we should ensure the stacktrace
  8. ## data isn't invalidated; any pointer into PFrame is
  9. ## subject to being invalidated so shouldn't be stored.
  10. when defined(nimStackTraceOverride):
  11. programCounter*: uint ## Program counter - will be used to get the rest of the info,
  12. ## when `$` is called on this type. We can't use
  13. ## "cuintptr_t" in here.
  14. 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

  1. 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

  1. string {.magic: String.}

Built-in string type. Source Edit

  1. TaintedString {....deprecated: "Deprecated since 1.5".} = string

Deprecated: Deprecated since 1.5

Source Edit

  1. TFrame {.importc, nodecl, final.} = object
  2. prev*: PFrame ## Previous frame; used for chaining the call stack.
  3. procname*: cstring ## Name of the proc that is currently executing.
  4. line*: int ## Line number of the proc that is currently executing.
  5. filename*: cstring ## Filename of the proc that is currently executing.
  6. len*: int16 ## Length of the inspectable slots.
  7. calldepth*: int16 ## Used for max call depth checking.
  8. when NimStackTraceMsgs:
  9. frameMsgLen*: int ## end position in frameMsgBuf for this frame.

The frame itself. Source Edit

  1. 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

  1. typed {.magic: Stmt.}

Meta type to denote an expression that is resolved (for templates). Source Edit

  1. typedesc {.magic: TypeDesc.}

Meta type to denote a type description. Source Edit

  1. TypeOfMode = enum
  2. typeOfProc, ## Prefer the interpretation that means `x` is a proc call.
  3. typeOfIter ## Prefer the interpretation that means `x` is an iterator call.

Possible modes of typeof. Source Edit

  1. uint {.magic: UInt.}

Unsigned default integer type. Source Edit

  1. uint8 {.magic: UInt8.}

Unsigned 8 bit integer type. Source Edit

  1. uint16 {.magic: UInt16.}

Unsigned 16 bit integer type. Source Edit

  1. uint32 {.magic: UInt32.}

Unsigned 32 bit integer type. Source Edit

  1. uint64 {.magic: UInt64.}

Unsigned 64 bit integer type. Source Edit

  1. UncheckedArray[T] {.magic: "UncheckedArray".}

Source Edit

  1. untyped {.magic: Expr.}

Meta type to denote an expression that is not resolved (for templates). Source Edit

  1. varargs[T] {.magic: "Varargs".}

Generic type to construct a varargs type. Source Edit

  1. void {.magic: "VoidType".}

Meta type to denote the absence of any type. Source Edit

Vars

  1. errorMessageWriter: (proc (msg: string) {....tags: [WriteIOEffect], gcsafe, nimcall.})

Function that will be called instead of stdmsg.write when printing stacktrace. Unstable API. Source Edit

  1. 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

  1. 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

  1. nimThreadDestructionHandlers {.threadvar.}: seq[
  2. proc () {.closure, ...gcsafe, raises: [].}]

Source Edit

  1. 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

  1. 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:

  1. var gOutOfMem: ref EOutOfMemory
  2. new(gOutOfMem) # need to be allocated *before* OOM really happened!
  3. gOutOfMem.msg = "out of memory"
  4. proc handleOOM() =
  5. raise gOutOfMem
  6. system.outOfMemHook = handleOOM

If the handler does not raise an exception, ordinary control flow continues and the program is terminated.

Source Edit

  1. programResult {.compilerproc, exportc: "nim_program_result".}: int

deprecated, prefer quit or exitprocs.getProgramResult, exitprocs.setProgramResult. Source Edit

  1. unhandledExceptionHook: proc (e: ref Exception) {.nimcall, ...tags: [], gcsafe,
  2. 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

  1. 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

  1. appType {.magic: "AppType".}: string = ""

A string that describes the application type. Possible values: “console”, “gui”, “lib”. Source Edit

  1. 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

  1. 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

  1. 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

  1. 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

  1. 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

  1. Inf = 0x7FF0000000000000'f64

Contains the IEEE floating point value of positive infinity. Source Edit

  1. 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

  1. 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

  1. NegInf = 0xFFF0000000000000'f64

Contains the IEEE floating point value of negative infinity. Source Edit

  1. NimMajor {.intdefine.}: int = 2

is the major number of Nim’s version. Example:

  1. when (NimMajor, NimMinor, NimPatch) >= (1, 3, 1): discard

Source Edit

  1. NimMinor {.intdefine.}: int = 0

is the minor number of Nim’s version. Odd for devel, even for releases. Source Edit

  1. NimPatch {.intdefine.}: int = 8

is the patch number of Nim’s version. Odd for devel, even for releases. Source Edit

  1. NimVersion: string = "2.0.8"

is the version of Nim as a string. Source Edit

  1. off = false

Alias for false. Source Edit

  1. on = true

Alias for true. Source Edit

  1. QuitFailure = 1

is the value that should be passed to quit to indicate failure. Source Edit

  1. QuitSuccess = 0

is the value that should be passed to quit to indicate success. Source Edit

Procs

  1. 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

  1. proc `%%`(x, y: int8): int8 {.inline, ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `%%`(x, y: int16): int16 {.inline, ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `%%`(x, y: int32): int32 {.inline, ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `%%`(x, y: int64): int64 {.inline, ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `&`(x, y: char): string {.magic: "ConStrStr", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Concatenates characters x and y into a string.

  1. assert('a' & 'b' == "ab")

Source Edit

  1. proc `&`(x, y: string): string {.magic: "ConStrStr", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Concatenates strings x and y.

  1. assert("ab" & "cd" == "abcd")

Source Edit

  1. proc `&`(x: char; y: string): string {.magic: "ConStrStr", noSideEffect,
  2. ...raises: [], tags: [], forbids: [].}

Concatenates x with y.

  1. assert('a' & "bc" == "abc")

Source Edit

  1. proc `&`(x: string; y: char): string {.magic: "ConStrStr", noSideEffect,
  2. ...raises: [], tags: [], forbids: [].}

Concatenates x with y.

  1. assert("ab" & 'c' == "abc")

Source Edit

  1. proc `&`[T](x, y: seq[T]): seq[T] {.noSideEffect.}

Concatenates two sequences.

Requires copying of the sequences.

  1. assert(@[1, 2, 3, 4] & @[5, 6] == @[1, 2, 3, 4, 5, 6])

See also:

Source Edit

  1. proc `&`[T](x: seq[T]; y: T): seq[T] {.noSideEffect.}

Appends element y to the end of the sequence.

Requires copying of the sequence.

  1. assert(@[1, 2, 3] & 4 == @[1, 2, 3, 4])

See also:

Source Edit

  1. proc `&`[T](x: T; y: seq[T]): seq[T] {.noSideEffect.}

Prepends the element x to the beginning of the sequence.

Requires copying of the sequence.

  1. assert(1 & @[2, 3, 4] == @[1, 2, 3, 4])

Source Edit

  1. proc `&=`(x: var string; y: string) {.magic: "AppendStrStr", noSideEffect,
  2. ...raises: [], tags: [], forbids: [].}

Appends in place to a string.

  1. var a = "abc"
  2. a &= "de" # a <- "abcde"

Source Edit

  1. proc `*`(x, y: float): float {.magic: "MulF64", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `*`(x, y: float32): float32 {.magic: "MulF64", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `*`(x, y: int): int {.magic: "MulI", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Binary * operator for an integer. Source Edit

  1. proc `*`(x, y: int8): int8 {.magic: "MulI", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Source Edit

  1. proc `*`(x, y: int16): int16 {.magic: "MulI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `*`(x, y: int32): int32 {.magic: "MulI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `*`(x, y: int64): int64 {.magic: "MulI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `*`(x, y: uint): uint {.magic: "MulU", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Binary * operator for unsigned integers. Source Edit

  1. proc `*`(x, y: uint8): uint8 {.magic: "MulU", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `*`(x, y: uint16): uint16 {.magic: "MulU", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `*`(x, y: uint32): uint32 {.magic: "MulU", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `*`(x, y: uint64): uint64 {.magic: "MulU", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. func `*`[T](x, y: set[T]): set[T] {.magic: "MulSet", ...raises: [], tags: [],
  2. forbids: [].}

This operator computes the intersection of two sets.

Example:

  1. assert {1, 2, 3} * {2, 3, 4} == {2, 3}

Source Edit

  1. 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

  1. proc `*%`(x, y: int8): int8 {.inline, ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `*%`(x, y: int16): int16 {.inline, ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `*%`(x, y: int32): int32 {.inline, ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `*%`(x, y: int64): int64 {.inline, ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `*=`[T: float | float32 | float64](x: var T; y: T) {.inline, noSideEffect.}

Multiplies in place a floating point number. Source Edit

  1. proc `*=`[T: SomeInteger](x: var T; y: T) {.inline, noSideEffect.}

Binary *= operator for integers. Source Edit

  1. proc `+`(x, y: float): float {.magic: "AddF64", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `+`(x, y: float32): float32 {.magic: "AddF64", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `+`(x, y: int): int {.magic: "AddI", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Binary + operator for an integer. Source Edit

  1. proc `+`(x, y: int8): int8 {.magic: "AddI", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Source Edit

  1. proc `+`(x, y: int16): int16 {.magic: "AddI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `+`(x, y: int32): int32 {.magic: "AddI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `+`(x, y: int64): int64 {.magic: "AddI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `+`(x, y: uint): uint {.magic: "AddU", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Binary + operator for unsigned integers. Source Edit

  1. proc `+`(x, y: uint8): uint8 {.magic: "AddU", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `+`(x, y: uint16): uint16 {.magic: "AddU", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `+`(x, y: uint32): uint32 {.magic: "AddU", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `+`(x, y: uint64): uint64 {.magic: "AddU", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `+`(x: float): float {.magic: "UnaryPlusF64", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `+`(x: float32): float32 {.magic: "UnaryPlusF64", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `+`(x: int): int {.magic: "UnaryPlusI", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Unary + operator for an integer. Has no effect. Source Edit

  1. proc `+`(x: int8): int8 {.magic: "UnaryPlusI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `+`(x: int16): int16 {.magic: "UnaryPlusI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `+`(x: int32): int32 {.magic: "UnaryPlusI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `+`(x: int64): int64 {.magic: "UnaryPlusI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. func `+`[T](x, y: set[T]): set[T] {.magic: "PlusSet", ...raises: [], tags: [],
  2. forbids: [].}

This operator computes the union of two sets.

Example:

  1. assert {1, 2, 3} + {2, 3, 4} == {1, 2, 3, 4}

Source Edit

  1. 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

  1. proc `+%`(x, y: int8): int8 {.inline, ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `+%`(x, y: int16): int16 {.inline, ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `+%`(x, y: int32): int32 {.inline, ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `+%`(x, y: int64): int64 {.inline, ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `+=`[T: float | float32 | float64](x: var T; y: T) {.inline, noSideEffect.}

Increments in place a floating point number. Source Edit

  1. proc `+=`[T: SomeInteger](x: var T; y: T) {.magic: "Inc", noSideEffect,
  2. ...raises: [], tags: [], forbids: [].}

Increments an integer. Source Edit

  1. proc `-`(a, b: AllocStats): AllocStats {....raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `-`(x, y: float): float {.magic: "SubF64", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `-`(x, y: float32): float32 {.magic: "SubF64", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `-`(x, y: int): int {.magic: "SubI", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Binary - operator for an integer. Source Edit

  1. proc `-`(x, y: int8): int8 {.magic: "SubI", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Source Edit

  1. proc `-`(x, y: int16): int16 {.magic: "SubI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `-`(x, y: int32): int32 {.magic: "SubI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `-`(x, y: int64): int64 {.magic: "SubI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `-`(x, y: uint): uint {.magic: "SubU", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Binary - operator for unsigned integers. Source Edit

  1. proc `-`(x, y: uint8): uint8 {.magic: "SubU", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `-`(x, y: uint16): uint16 {.magic: "SubU", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `-`(x, y: uint32): uint32 {.magic: "SubU", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `-`(x, y: uint64): uint64 {.magic: "SubU", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `-`(x: float): float {.magic: "UnaryMinusF64", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `-`(x: float32): float32 {.magic: "UnaryMinusF64", noSideEffect,
  2. ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `-`(x: int): int {.magic: "UnaryMinusI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Unary - operator for an integer. Negates x. Source Edit

  1. proc `-`(x: int8): int8 {.magic: "UnaryMinusI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `-`(x: int16): int16 {.magic: "UnaryMinusI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `-`(x: int32): int32 {.magic: "UnaryMinusI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `-`(x: int64): int64 {.magic: "UnaryMinusI64", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. func `-`[T](x, y: set[T]): set[T] {.magic: "MinusSet", ...raises: [], tags: [],
  2. forbids: [].}

This operator computes the difference of two sets.

Example:

  1. assert {1, 2, 3} - {2, 3, 4} == {1}

Source Edit

  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.

Source Edit

  1. proc `-%`(x, y: int8): int8 {.inline, ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `-%`(x, y: int16): int16 {.inline, ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `-%`(x, y: int32): int32 {.inline, ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `-%`(x, y: int64): int64 {.inline, ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `-=`[T: float | float32 | float64](x: var T; y: T) {.inline, noSideEffect.}

Decrements in place a floating point number. Source Edit

  1. proc `-=`[T: SomeInteger](x: var T; y: T) {.magic: "Dec", noSideEffect,
  2. ...raises: [], tags: [], forbids: [].}

Decrements an integer. Source Edit

  1. proc `..`[T, U](a: sink T; b: sink U): HSlice[T, U] {.noSideEffect, inline,
  2. 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.

  1. let a = [10, 20, 30, 40, 50]
  2. echo a[2 .. 3] # @[30, 40]

Source Edit

  1. proc `..`[T](b: sink T): HSlice[int, T] {.noSideEffect, inline, magic: "DotDot",
  2. ...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].

  1. let a = [10, 20, 30, 40, 50]
  2. echo a[.. 2] # @[10, 20, 30]

Source Edit

  1. proc `/`(x, y: float): float {.magic: "DivF64", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `/`(x, y: float32): float32 {.magic: "DivF64", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `/`(x, y: int): float {.inline, noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Division of integers that results in a float.

  1. echo 7 / 5 # => 1.4

See also:

Source Edit

  1. 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

  1. proc `/%`(x, y: int8): int8 {.inline, ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `/%`(x, y: int16): int16 {.inline, ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `/%`(x, y: int32): int32 {.inline, ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `/%`(x, y: int64): int64 {.inline, ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `/=`(x: var float64; y: float64) {.inline, noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Divides in place a floating point number. Source Edit

  1. proc `/=`[T: float | float32](x: var T; y: T) {.inline, noSideEffect.}

Divides in place a floating point number. Source Edit

  1. proc `<`(x, y: bool): bool {.magic: "LtB", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Source Edit

  1. proc `<`(x, y: char): bool {.magic: "LtCh", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Compares two chars and returns true if x is lexicographically before y (uppercase letters come before lowercase letters).

Example:

  1. let
  2. a = 'a'
  3. b = 'b'
  4. c = 'Z'
  5. assert a < b
  6. assert not (a < a)
  7. assert not (a < c)

Source Edit

  1. proc `<`(x, y: float): bool {.magic: "LtF64", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `<`(x, y: float32): bool {.magic: "LtF64", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `<`(x, y: int): bool {.magic: "LtI", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Returns true if x is less than y. Source Edit

  1. proc `<`(x, y: int8): bool {.magic: "LtI", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Source Edit

  1. proc `<`(x, y: int16): bool {.magic: "LtI", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Source Edit

  1. proc `<`(x, y: int32): bool {.magic: "LtI", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Source Edit

  1. proc `<`(x, y: int64): bool {.magic: "LtI", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Source Edit

  1. proc `<`(x, y: pointer): bool {.magic: "LtPtr", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `<`(x, y: string): bool {.magic: "LtStr", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Compares two strings and returns true if x is lexicographically before y (uppercase letters come before lowercase letters).

Example:

  1. let
  2. a = "abc"
  3. b = "abd"
  4. c = "ZZZ"
  5. assert a < b
  6. assert not (a < a)
  7. assert not (a < c)

Source Edit

  1. proc `<`(x, y: uint): bool {.magic: "LtU", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Returns true if x < y. Source Edit

  1. proc `<`(x, y: uint8): bool {.magic: "LtU", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Source Edit

  1. proc `<`(x, y: uint16): bool {.magic: "LtU", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Source Edit

  1. proc `<`(x, y: uint32): bool {.magic: "LtU", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Source Edit

  1. proc `<`(x, y: uint64): bool {.magic: "LtU", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Source Edit

  1. proc `<`[Enum: enum](x, y: Enum): bool {.magic: "LtEnum", noSideEffect,
  2. ...raises: [], tags: [], forbids: [].}

Source Edit

  1. 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

  1. proc `<`[T](x, y: ptr T): bool {.magic: "LtPtr", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `<`[T](x, y: ref T): bool {.magic: "LtPtr", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `<`[T](x, y: set[T]): bool {.magic: "LtSet", noSideEffect, ...raises: [],
  2. 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:

  1. let
  2. a = {3, 5}
  3. b = {1, 3, 5, 7}
  4. c = {2}
  5. assert a < b
  6. assert not (a < a)
  7. assert not (a < c)

Source Edit

  1. 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

  1. proc `<%`(x, y: int8): bool {.inline, ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `<%`(x, y: int16): bool {.inline, ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `<%`(x, y: int32): bool {.inline, ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `<%`(x, y: int64): bool {.inline, ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `<=`(x, y: bool): bool {.magic: "LeB", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Source Edit

  1. proc `<=`(x, y: char): bool {.magic: "LeCh", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Compares two chars and returns true if x is lexicographically before y (uppercase letters come before lowercase letters).

Example:

  1. let
  2. a = 'a'
  3. b = 'b'
  4. c = 'Z'
  5. assert a <= b
  6. assert a <= a
  7. assert not (a <= c)

Source Edit

  1. proc `<=`(x, y: float): bool {.magic: "LeF64", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `<=`(x, y: float32): bool {.magic: "LeF64", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `<=`(x, y: int): bool {.magic: "LeI", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Returns true if x is less than or equal to y. Source Edit

  1. proc `<=`(x, y: int8): bool {.magic: "LeI", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Source Edit

  1. proc `<=`(x, y: int16): bool {.magic: "LeI", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Source Edit

  1. proc `<=`(x, y: int32): bool {.magic: "LeI", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Source Edit

  1. proc `<=`(x, y: int64): bool {.magic: "LeI", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Source Edit

  1. proc `<=`(x, y: pointer): bool {.magic: "LePtr", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `<=`(x, y: string): bool {.magic: "LeStr", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Compares two strings and returns true if x is lexicographically before y (uppercase letters come before lowercase letters).

Example:

  1. let
  2. a = "abc"
  3. b = "abd"
  4. c = "ZZZ"
  5. assert a <= b
  6. assert a <= a
  7. assert not (a <= c)

Source Edit

  1. proc `<=`(x, y: uint): bool {.magic: "LeU", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Returns true if x <= y. Source Edit

  1. proc `<=`(x, y: uint8): bool {.magic: "LeU", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Source Edit

  1. proc `<=`(x, y: uint16): bool {.magic: "LeU", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `<=`(x, y: uint32): bool {.magic: "LeU", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `<=`(x, y: uint64): bool {.magic: "LeU", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `<=`[Enum: enum](x, y: Enum): bool {.magic: "LeEnum", noSideEffect,
  2. ...raises: [], tags: [], forbids: [].}

Source Edit

  1. 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

  1. proc `<=`[T](x, y: ref T): bool {.magic: "LePtr", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `<=`[T](x, y: set[T]): bool {.magic: "LeSet", noSideEffect, ...raises: [],
  2. 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:

  1. let
  2. a = {3, 5}
  3. b = {1, 3, 5, 7}
  4. c = {2}
  5. assert a <= b
  6. assert a <= a
  7. assert not (a <= c)

Source Edit

  1. 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

  1. proc `<=%`(x, y: int8): bool {.inline, ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `<=%`(x, y: int16): bool {.inline, ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `<=%`(x, y: int32): bool {.inline, ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `<=%`(x, y: int64): bool {.inline, ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `=`[T](dest: var T; src: T) {.noSideEffect, magic: "Asgn", ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `==`(x, y: bool): bool {.magic: "EqB", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Checks for equality between two bool variables. Source Edit

  1. proc `==`(x, y: char): bool {.magic: "EqCh", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Checks for equality between two char variables. Source Edit

  1. proc `==`(x, y: cstring): bool {.magic: "EqCString", noSideEffect, inline,
  2. ...raises: [], tags: [], forbids: [].}

Checks for equality between two cstring variables. Source Edit

  1. proc `==`(x, y: float): bool {.magic: "EqF64", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `==`(x, y: float32): bool {.magic: "EqF64", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `==`(x, y: int): bool {.magic: "EqI", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Compares two integers for equality. Source Edit

  1. proc `==`(x, y: int8): bool {.magic: "EqI", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Source Edit

  1. proc `==`(x, y: int16): bool {.magic: "EqI", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Source Edit

  1. proc `==`(x, y: int32): bool {.magic: "EqI", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Source Edit

  1. proc `==`(x, y: int64): bool {.magic: "EqI", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Source Edit

  1. proc `==`(x, y: pointer): bool {.magic: "EqRef", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Checks for equality between two pointer variables.

Example:

  1. var # this is a wildly dangerous example
  2. a = cast[pointer](0)
  3. b = cast[pointer](nil)
  4. assert a == b # true due to the special meaning of `nil`/0 as a pointer

Source Edit

  1. proc `==`(x, y: string): bool {.magic: "EqStr", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Checks for equality between two string variables. Source Edit

  1. proc `==`(x, y: uint): bool {.magic: "EqI", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Compares two unsigned integers for equality. Source Edit

  1. proc `==`(x, y: uint8): bool {.magic: "EqI", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Source Edit

  1. proc `==`(x, y: uint16): bool {.magic: "EqI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `==`(x, y: uint32): bool {.magic: "EqI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `==`(x, y: uint64): bool {.magic: "EqI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `==`[Enum: enum](x, y: Enum): bool {.magic: "EqEnum", noSideEffect,
  2. ...raises: [], tags: [], forbids: [].}

Checks whether values within the same enum have the same underlying value.

Example:

  1. type
  2. Enum1 = enum
  3. field1 = 3, field2
  4. Enum2 = enum
  5. place1, place2 = 3
  6. var
  7. e1 = field1
  8. e2 = place2.ord.Enum1
  9. assert e1 == e2
  10. assert not compiles(e1 == place2) # raises error

Source Edit

  1. proc `==`[I, T](x, y: array[I, T]): bool

Source Edit

  1. proc `==`[T: proc | iterator](x, y: T): bool {.magic: "EqProc", noSideEffect,
  2. ...raises: [], tags: [], forbids: [].}

Checks that two proc variables refer to the same procedure. Source Edit

  1. proc `==`[T: tuple | object](x, y: T): bool

Generic \== operator for tuples that is lifted from the components. of x and y. Source Edit

  1. proc `==`[T](x, y: openArray[T]): bool

Source Edit

  1. proc `==`[T](x, y: ptr T): bool {.magic: "EqRef", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Checks that two ptr variables refer to the same item. Source Edit

  1. proc `==`[T](x, y: ref T): bool {.magic: "EqRef", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Checks that two ref variables refer to the same item. Source Edit

  1. 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

  1. proc `==`[T](x, y: set[T]): bool {.magic: "EqSet", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Checks for equality between two variables of type set.

Example:

  1. assert {1, 2, 2, 3} == {1, 2, 3} # duplication in sets is ignored

Source Edit

  1. proc `=copy`[T](dest: var T; src: T) {.noSideEffect, magic: "Asgn", ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `=destroy`[T](x: var T) {.inline, magic: "Destroy", ...raises: [], tags: [],
  2. forbids: [].}

Generic destructor implementation that can be overridden. Source Edit

  1. proc `=dup`[T](x: T): T {.inline, magic: "Dup", ...raises: [], tags: [],
  2. forbids: [].}

Generic dup implementation that can be overridden. Source Edit

  1. proc `=sink`[T](x: var T; y: T) {.inline, nodestroy, magic: "Asgn", ...raises: [],
  2. tags: [], forbids: [].}

Generic sink implementation that can be overridden. Source Edit

  1. proc `=trace`[T](x: var T; env: pointer) {.inline, magic: "Trace", ...raises: [],
  2. tags: [], forbids: [].}

Generic trace implementation that can be overridden. Source Edit

  1. proc `=wasMoved`[T](obj: var T) {.magic: "WasMoved", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Generic wasMoved implementation that can be overridden. Source Edit

  1. proc `@`[IDX, T](a: sink array[IDX, T]): seq[T] {.magic: "ArrToSeq",
  2. 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].

  1. let
  2. a = [1, 3, 5]
  3. b = "foo"
  4. echo @a # => @[1, 3, 5]
  5. echo @b # => @['f', 'o', 'o']

Source Edit

  1. proc `@`[T](a: openArray[T]): seq[T] {.magic: "OpenArrayToSeq", ...raises: [],
  2. 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

  1. proc `[]`(s: string; i: BackwardsIndex): char {.inline, systemRaisesDefect,
  2. ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `[]`(s: var string; i: BackwardsIndex): var char {.inline,
  2. systemRaisesDefect, ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `[]`[I: Ordinal; T](a: T; i: I): T {.noSideEffect, magic: "ArrGet",
  2. ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `[]`[Idx, T; U, V: Ordinal](a: array[Idx, T]; x: HSlice[U, V]): seq[T] {.
  2. systemRaisesDefect.}

Slice operation for arrays. Returns the inclusive range [a[x.a], a[x.b]]:

  1. var a = [1, 2, 3, 4]
  2. assert a[0..2] == @[1, 2, 3]

Source Edit

  1. proc `[]`[Idx, T](a: array[Idx, T]; i: BackwardsIndex): T {.inline,
  2. systemRaisesDefect.}

Source Edit

  1. proc `[]`[Idx, T](a: var array[Idx, T]; i: BackwardsIndex): var T {.inline,
  2. systemRaisesDefect.}

Source Edit

  1. proc `[]`[T, U: Ordinal](s: string; x: HSlice[T, U]): string {.inline,
  2. systemRaisesDefect.}

Slice operation for strings. Returns the inclusive range [s[x.a], s[x.b]]:

  1. var s = "abcdef"
  2. assert s[1..3] == "bcd"

Source Edit

  1. proc `[]`[T; U, V: Ordinal](s: openArray[T]; x: HSlice[U, V]): seq[T] {.
  2. systemRaisesDefect.}

Slice operation for sequences. Returns the inclusive range [s[x.a], s[x.b]]:

  1. var s = @[1, 2, 3, 4]
  2. assert s[0..2] == @[1, 2, 3]

Source Edit

  1. proc `[]`[T](s: openArray[T]; i: BackwardsIndex): T {.inline, systemRaisesDefect.}

Source Edit

  1. proc `[]`[T](s: var openArray[T]; i: BackwardsIndex): var T {.inline,
  2. systemRaisesDefect.}

Source Edit

  1. proc `[]=`(s: var string; i: BackwardsIndex; x: char) {.inline,
  2. systemRaisesDefect, ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `[]=`[I: Ordinal; T, S](a: T; i: I; x: sink S) {.noSideEffect,
  2. magic: "ArrPut", ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `[]=`[Idx, T; U, V: Ordinal](a: var array[Idx, T]; x: HSlice[U, V];
  2. b: openArray[T]) {.systemRaisesDefect.}

Slice assignment for arrays.

  1. var a = [10, 20, 30, 40, 50]
  2. a[1..2] = @[99, 88]
  3. assert a == [10, 99, 88, 40, 50]

Source Edit

  1. proc `[]=`[Idx, T](a: var array[Idx, T]; i: BackwardsIndex; x: T) {.inline,
  2. systemRaisesDefect.}

Source Edit

  1. proc `[]=`[T, U: Ordinal](s: var string; x: HSlice[T, U]; b: string) {.
  2. 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:

  1. var s = "abcdefgh"
  2. s[1 .. ^2] = "xyz"
  3. assert s == "axyzh"

Source Edit

  1. proc `[]=`[T; U, V: Ordinal](s: var seq[T]; x: HSlice[U, V]; b: openArray[T]) {.
  2. 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:

  1. var s = @"abcdefgh"
  2. s[1 .. ^2] = @"xyz"
  3. assert s == @"axyzh"

Source Edit

  1. proc `[]=`[T](s: var openArray[T]; i: BackwardsIndex; x: T) {.inline,
  2. systemRaisesDefect.}

Source Edit

  1. func abs(x: int): int {.magic: "AbsI", inline, ...raises: [], tags: [], forbids: [].}

Source Edit

  1. func abs(x: int8): int8 {.magic: "AbsI", inline, ...raises: [], tags: [],
  2. forbids: [].}

Source Edit

  1. func abs(x: int16): int16 {.magic: "AbsI", inline, ...raises: [], tags: [],
  2. forbids: [].}

Source Edit

  1. func abs(x: int32): int32 {.magic: "AbsI", inline, ...raises: [], tags: [],
  2. forbids: [].}

Source Edit

  1. func abs(x: int64): int64 {.magic: "AbsI", inline, ...raises: [], tags: [],
  2. 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

  1. proc abs[T: float64 | float32](x: T): T {.noSideEffect, inline.}

Source Edit

  1. proc add(x: var cstring; y: cstring) {.magic: "AppendStrStr", ...raises: [],
  2. tags: [], forbids: [].}

Appends y to x in place. Only implemented for JS backend.

Example:

  1. when defined(js):
  2. var tmp: cstring = ""
  3. tmp.add(cstring("ab"))
  4. tmp.add(cstring("cd"))
  5. doAssert tmp == cstring("abcd")

Source Edit

  1. proc add(x: var string; y: char) {.magic: "AppendStrCh", noSideEffect,
  2. ...raises: [], tags: [], forbids: [].}

Appends y to x in place.

  1. var tmp = ""
  2. tmp.add('a')
  3. tmp.add('b')
  4. assert(tmp == "ab")

Source Edit

  1. proc add(x: var string; y: cstring) {.asmNoStackFrame, ...raises: [], tags: [],
  2. forbids: [].}

Appends y to x in place.

Example:

  1. var tmp = ""
  2. tmp.add(cstring("ab"))
  3. tmp.add(cstring("cd"))
  4. doAssert tmp == "abcd"

Source Edit

  1. proc add(x: var string; y: string) {.magic: "AppendStrStr", noSideEffect,
  2. ...raises: [], tags: [], forbids: [].}

Concatenates x and y in place.

See also strbasics.add.

Example:

  1. var tmp = ""
  2. tmp.add("ab")
  3. tmp.add("cd")
  4. assert tmp == "abcd"

Source Edit

  1. 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:

  1. var a = @["a1", "a2"]
  2. a.add(["b1", "b2"])
  3. assert a == @["a1", "a2", "b1", "b2"]
  4. var c = @["c0", "c1", "c2", "c3"]
  5. a.add(c.toOpenArray(1, 2))
  6. assert a == @["a1", "a2", "b1", "b2", "c1", "c2"]

Source Edit

  1. proc add[T](x: var seq[T]; y: sink T) {.magic: "AppendSeqElem", noSideEffect,
  2. ...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.

  1. var s: seq[string] = @["test2","test2"]
  2. s.add("test")
  3. assert s == @["test2", "test2", "test"]

Source Edit

  1. proc addEscapedChar(s: var string; c: char) {.noSideEffect, inline, ...raises: [],
  2. 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

  1. proc addQuitProc(quitProc: proc () {.noconv.}) {.importc: "atexit",
  2. header: "<stdlib.h>", ...deprecated: "use exitprocs.addExitProc", raises: [],
  3. 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.

Source Edit

  1. 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.

  1. var tmp = ""
  2. tmp.addQuoted(1)
  3. tmp.add(", ")
  4. tmp.addQuoted("string")
  5. tmp.add(", ")
  6. tmp.addQuoted('c')
  7. assert(tmp == """1, "string", 'c'""")

Source Edit

  1. proc `addr`[T](x: T): ptr T {.magic: "Addr", noSideEffect, ...raises: [], tags: [],
  2. 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.

  1. var
  2. buf: seq[char] = @['a','b','c']
  3. p = buf[1].addr
  4. echo p.repr # ref 0x7faa35c40059 --> 'b'
  5. echo p[] # b

Source Edit

  1. proc alignof(x: typedesc): int {.magic: "AlignOf", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc alignof[T](x: T): int {.magic: "AlignOf", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc alloc0Impl(size: Natural): pointer {.noconv, ...gcsafe, tags: [], gcsafe,
  2. raises: [], forbids: [].}

Source Edit

  1. proc allocCStringArray(a: openArray[string]): cstringArray {....raises: [],
  2. 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

  1. proc allocImpl(size: Natural): pointer {.noconv, ...gcsafe, tags: [], gcsafe,
  2. raises: [], forbids: [].}

Source Edit

  1. proc allocShared0Impl(size: Natural): pointer {.noconv, ...gcsafe, gcsafe,
  2. raises: [], tags: [], forbids: [].}

Source Edit

  1. proc allocSharedImpl(size: Natural): pointer {.noconv, compilerproc, ...gcsafe,
  2. gcsafe, raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `and`(a, b: typedesc): typedesc {.magic: "TypeTrait", noSideEffect,
  2. ...raises: [], tags: [], forbids: [].}

Constructs an and meta class. Source Edit

  1. proc `and`(x, y: bool): bool {.magic: "And", noSideEffect, ...raises: [], tags: [],
  2. 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

  1. proc `and`(x, y: int): int {.magic: "BitandI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Computes the bitwise and of numbers x and y.

Example:

  1. assert (0b0011 and 0b0101) == 0b0001
  2. assert (0b0111 and 0b1100) == 0b0100

Source Edit

  1. proc `and`(x, y: int8): int8 {.magic: "BitandI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `and`(x, y: int16): int16 {.magic: "BitandI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `and`(x, y: int32): int32 {.magic: "BitandI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `and`(x, y: int64): int64 {.magic: "BitandI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `and`(x, y: uint): uint {.magic: "BitandI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Computes the bitwise and of numbers x and y. Source Edit

  1. proc `and`(x, y: uint8): uint8 {.magic: "BitandI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `and`(x, y: uint16): uint16 {.magic: "BitandI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `and`(x, y: uint32): uint32 {.magic: "BitandI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `and`(x, y: uint64): uint64 {.magic: "BitandI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc arrayWith[T](y: T; size: static int): array[size, T] {....raises: [].}

Creates a new array filled with y. Source Edit

  1. proc ashr(x: int8; y: SomeInteger): int8 {.magic: "AshrI", noSideEffect,
  2. ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc ashr(x: int16; y: SomeInteger): int16 {.magic: "AshrI", noSideEffect,
  2. ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc ashr(x: int32; y: SomeInteger): int32 {.magic: "AshrI", noSideEffect,
  2. ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc ashr(x: int64; y: SomeInteger): int64 {.magic: "AshrI", noSideEffect,
  2. ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc ashr(x: int; y: SomeInteger): int {.magic: "AshrI", noSideEffect,
  2. ...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:

  1. assert ashr(0b0001_0000'i8, 2) == 0b0000_0100'i8
  2. assert ashr(0b1000_0000'i8, 8) == 0b1111_1111'i8
  3. assert ashr(0b1000_0000'i8, 1) == 0b1100_0000'i8

Source Edit

  1. proc astToStr[T](x: T): string {.magic: "AstToStr", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Converts the AST of x into a string representation. This is very useful for debugging. Source Edit

  1. func capacity(self: string): int {.inline, ...raises: [], tags: [], forbids: [].}

Returns the current capacity of the string.

Example:

  1. var str = newStringOfCap(cap = 42)
  2. str.add "Nim"
  3. assert str.capacity == 42

Source Edit

  1. func capacity[T](self: seq[T]): int {.inline.}

Returns the current capacity of the seq.

Example:

  1. var lst = newSeqOfCap[string](cap = 42)
  2. lst.add "Nim"
  3. assert lst.capacity == 42

Source Edit

  1. 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:

  1. var a = {1, 3, 5, 7}
  2. assert card(a) == 4
  3. var b = {1, 3, 5, 7, 5}
  4. assert card(b) == 4 # repeated 5 doesn't count

Source Edit

  1. func chr(u: range[0 .. 255]): char {.magic: "Chr", ...raises: [], tags: [],
  2. forbids: [].}

Converts u to a char, same as char(u).

Example:

  1. doAssert chr(65) == 'A'
  2. doAssert chr(255) == '\255'
  3. doAssert chr(255) == char(255)
  4. doAssert not compiles chr(256)
  5. doAssert not compiles char(256)
  6. var x = 256
  7. doAssertRaises(RangeDefect): discard chr(x)
  8. doAssertRaises(RangeDefect): discard char(x)

Source Edit

  1. 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:

  1. assert (1.4).clamp(0.0, 1.0) == 1.0
  2. assert (0.5).clamp(0.0, 1.0) == 0.5
  3. assert 4.clamp(1, 3) == max(1, min(3, 4))

Source Edit

  1. proc close[TMsg](c: var Channel[TMsg])

Closes a channel c and frees its associated resources. Source Edit

  1. 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

  1. 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.

  1. import std/algorithm
  2. echo sorted(@[4, 2, 6, 5, 8, 7], cmp[int])

Source Edit

  1. proc cmpMem(a, b: pointer; size: Natural): int {.inline, noSideEffect, ...tags: [],
  2. 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

  1. proc compileOption(option, arg: string): bool {.magic: "CompileOptionArg",
  2. noSideEffect, ...raises: [], tags: [], forbids: [].}

Can be used to determine an enum compile-time option.

See also:

Example:

  1. when compileOption("opt", "size") and compileOption("gc", "boehm"):
  2. discard "compiled with optimization for size and uses Boehm's GC"

Source Edit

  1. proc compileOption(option: string): bool {.magic: "CompileOption", noSideEffect,
  2. ...raises: [], tags: [], forbids: [].}

Can be used to determine an on|off compile-time option.

See also:

Example: cmd: —floatChecks:off

  1. static: doAssert not compileOption("floatchecks")
  2. {.push floatChecks: on.}
  3. static: doAssert compileOption("floatchecks")
  4. # floating point NaN and Inf checks enabled in this scope
  5. {.pop.}

Source Edit

  1. proc compiles(x: untyped): bool {.magic: "Compiles", noSideEffect, compileTime,
  2. ...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:

  1. when compiles(3 + 4):
  2. echo "'+' for integers is available"

Source Edit

  1. 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.

  1. var a = @[1, 3, 5]
  2. assert a.contains(5)
  3. assert 3 in a
  4. assert 99 notin a

Source Edit

  1. func contains[T](x: set[T]; y: T): bool {.magic: "InSet", ...raises: [], tags: [],
  2. 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:

  1. var s: set[range['a'..'z']] = {'a'..'c'}
  2. assert s.contains('c')
  3. assert 'b' in s
  4. assert 'd' notin s
  5. 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

  1. 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.

  1. assert((1..3).contains(1) == true)
  2. assert((1..3).contains(2) == true)
  3. assert((1..3).contains(4) == false)

Source Edit

  1. proc copyMem(dest, source: pointer; size: Natural) {.inline, ...gcsafe, tags: [],
  2. 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

  1. proc create(T: typedesc; size = 1.Positive): ptr T:type {.inline, ...gcsafe,
  2. 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

  1. 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

  1. proc createSharedU(T: typedesc; size = 1.Positive): ptr T:type {.inline,
  2. ...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

  1. proc createU(T: typedesc; size = 1.Positive): ptr T:type {.inline, ...gcsafe,
  2. 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

  1. proc cstringArrayToSeq(a: cstringArray): seq[string] {....raises: [], tags: [],
  2. forbids: [].}

Converts a cstringArray to a seq[string]. a is supposed to be terminated by nil. Source Edit

  1. proc cstringArrayToSeq(a: cstringArray; len: Natural): seq[string] {....raises: [],
  2. tags: [], forbids: [].}

Converts a cstringArray to a seq[string]. a is supposed to be of length len. Source Edit

  1. proc dealloc(p: pointer) {.noconv, compilerproc, ...gcsafe, gcsafe, raises: [],
  2. 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

  1. proc deallocCStringArray(a: cstringArray) {....raises: [], tags: [], forbids: [].}

Frees a NULL terminated cstringArray. Source Edit

  1. proc deallocHeap(runFinalizers = true; allowGcAfterwards = true) {....raises: [],
  2. tags: [RootEffect], forbids: [].}

Frees the thread local heap. Runs every finalizer if runFinalizers is true. If allowGcAfterwards is true, a minimal amount of allocation happens to ensure the GC can continue to work after the call to deallocHeap. Source Edit

  1. proc deallocImpl(p: pointer) {.noconv, ...gcsafe, tags: [], gcsafe, raises: [],
  2. forbids: [].}

Source Edit

  1. proc deallocShared(p: pointer) {.noconv, compilerproc, ...gcsafe, gcsafe,
  2. 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

  1. proc deallocSharedImpl(p: pointer) {.noconv, ...gcsafe, gcsafe, raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc debugEcho(x: varargs[typed, `$`]) {.magic: "Echo", noSideEffect, ...tags: [],
  2. 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

  1. proc dec[T, V: Ordinal](x: var T; y: V = 1) {.magic: "Dec", noSideEffect,
  2. ...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:

  1. var i = 2
  2. dec(i)
  3. assert i == 1
  4. dec(i, 3)
  5. assert i == -2

Source Edit

  1. proc declared(x: untyped): bool {.magic: "Declared", noSideEffect, compileTime,
  2. ...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:

  1. when not declared(strutils.toUpper):
  2. # provide our own toUpper proc here, because strutils is
  3. # missing it.

See also:

Source Edit

  1. proc declaredInScope(x: untyped): bool {.magic: "DeclaredInScope", noSideEffect,
  2. 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

  1. proc deepCopy[T](x: var T; y: T) {.noSideEffect, magic: "DeepCopy", ...raises: [],
  2. 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

  1. proc deepCopy[T](y: T): T

Convenience wrapper around deepCopy overload. Source Edit

  1. proc default[T](_: typedesc[T]): T {.magic: "Default", noSideEffect, ...raises: [],
  2. 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

  1. assert (int, float).default == (0, 0.0)
  2. type Foo = object
  3. a: range[2..6]
  4. var x = Foo.default
  5. assert x.a == 2

Source Edit

  1. proc defined(x: untyped): bool {.magic: "Defined", noSideEffect, compileTime,
  2. ...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:

  1. when not defined(release):
  2. # Do here programmer friendly expensive sanity checks.
  3. # Put here the normal code

See also:

Source Edit

  1. 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:

  1. var a = @[10, 11, 12, 13, 14]
  2. a.del(2)
  3. assert a == @[10, 11, 14, 13]

Source Edit

  1. proc delete[T](x: var seq[T]; i: Natural) {.noSideEffect.}

Deletes the item at index i by moving all x[i+1..^1] items by one position.

This is an O(n) operation.

Note: With -d:nimStrictDelete, an index error is produced when the index passed to it was out of bounds. -d:nimStrictDelete will become the default in upcoming versions.

See also:

  • del for O(1) operation

Example:

  1. var s = @[1, 2, 3, 4, 5]
  2. s.delete(2)
  3. doAssert s == @[1, 2, 4, 5]

Source Edit

  1. proc dispose(x: ForeignCell) {....raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `div`(x, y: int): int {.magic: "DivI", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Computes the integer division.

This is roughly the same as math.trunc(x/y).int.

Example:

  1. assert (1 div 2) == 0
  2. assert (2 div 2) == 1
  3. assert (3 div 2) == 1
  4. assert (7 div 3) == 2
  5. assert (-7 div 3) == -2
  6. assert (7 div -3) == -2
  7. assert (-7 div -3) == 2

Source Edit

  1. proc `div`(x, y: int8): int8 {.magic: "DivI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `div`(x, y: int16): int16 {.magic: "DivI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `div`(x, y: int32): int32 {.magic: "DivI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `div`(x, y: int64): int64 {.magic: "DivI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `div`(x, y: uint): uint {.magic: "DivU", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Computes the integer division for unsigned integers. This is roughly the same as trunc(x/y). Source Edit

  1. proc `div`(x, y: uint8): uint8 {.magic: "DivU", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `div`(x, y: uint16): uint16 {.magic: "DivU", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `div`(x, y: uint32): uint32 {.magic: "DivU", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `div`(x, y: uint64): uint64 {.magic: "DivU", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc echo(x: varargs[typed, `$`]) {.magic: "Echo", ...gcsafe, sideEffect,
  2. ...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

  1. proc ensureMove[T](x: T): T {.magic: "EnsureMove", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Ensures that x is moved to the new location, otherwise it gives an error at the compile time.

Example:

  1. proc foo =
  2. var x = "Hello"
  3. let y = ensureMove(x)
  4. doAssert y == "Hello"
  5. foo()

Source Edit

  1. proc equalMem(a, b: pointer; size: Natural): bool {.inline, noSideEffect,
  2. ...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

  1. func excl[T](x: var set[T]; y: T) {.magic: "Excl", ...raises: [], tags: [],
  2. forbids: [].}

Excludes element y from the set x.

This is the same as x = x - {y}, but it might be more efficient.

Example:

  1. var b = {2, 3, 5, 6, 12, 54}
  2. b.excl(5)
  3. assert b == {2, 3, 6, 12, 54}

Source Edit

  1. 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

  1. proc finished[T: iterator {.closure.}](x: T): bool {.noSideEffect, inline,
  2. magic: "Finished", ...raises: [], tags: [], forbids: [].}

It can be used to determine if a first class iterator has finished. Source Edit

  1. 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

  1. proc GC_collectZct() {....raises: [], tags: [RootEffect], forbids: [].}

Collect the ZCT (zero count table). Unstable, experimental API for testing purposes. DO NOT USE! Source Edit

  1. proc GC_disable() {....gcsafe, inline, ...gcsafe, raises: [], tags: [], forbids: [].}

Disables the GC. If called n times, n calls to GC_enable are needed to reactivate the GC.

Note that in most circumstances one should only disable the mark and sweep phase with GC_disableMarkAndSweep.

Source Edit

  1. proc GC_disableMarkAndSweep() {....gcsafe, gcsafe, raises: [], tags: [],
  2. forbids: [].}

The current implementation uses a reference counting garbage collector with a seldomly run mark and sweep phase to free cycles. The mark and sweep phase may take a long time and is not needed if the application does not create cycles. Thus the mark and sweep phase can be deactivated and activated separately from the rest of the GC. Source Edit

  1. proc GC_enable() {....gcsafe, inline, ...gcsafe, raises: [], tags: [], forbids: [].}

Enables the GC again. Source Edit

  1. proc GC_enableMarkAndSweep() {....gcsafe, gcsafe, raises: [], tags: [], forbids: [].}

Source Edit

  1. proc GC_fullCollect() {....gcsafe, gcsafe, raises: [], tags: [RootEffect],
  2. forbids: [].}

Forces a full garbage collection pass. Ordinary code does not need to call this (and should not). Source Edit

  1. proc GC_getStatistics(): string {....gcsafe, gcsafe, raises: [], tags: [],
  2. forbids: [].}

Returns an informative string about the GC’s activity. This may be useful for tweaking. Source Edit

  1. proc GC_ref(x: string) {.magic: "GCref", ...gcsafe, raises: [], tags: [],
  2. forbids: [].}

Marks the object x as referenced, so that it will not be freed until it is unmarked via GC_unref. If called n-times for the same object x, n calls to GC_unref are needed to unmark x. Source Edit

  1. proc GC_ref[T](x: ref T) {.magic: "GCref", ...gcsafe, raises: [], tags: [],
  2. forbids: [].}

Source Edit

  1. proc GC_ref[T](x: seq[T]) {.magic: "GCref", ...gcsafe, raises: [], tags: [],
  2. forbids: [].}

Source Edit

  1. proc GC_unref(x: string) {.magic: "GCunref", ...gcsafe, raises: [], tags: [],
  2. forbids: [].}

See the documentation of GC_ref. Source Edit

  1. proc GC_unref[T](x: ref T) {.magic: "GCunref", ...gcsafe, raises: [], tags: [],
  2. forbids: [].}

Source Edit

  1. proc GC_unref[T](x: seq[T]) {.magic: "GCunref", ...gcsafe, raises: [], tags: [],
  2. forbids: [].}

Source Edit

  1. proc gcInvariant() {....raises: [], tags: [], forbids: [].}

Source Edit

  1. proc getAllocStats(): AllocStats {....raises: [], tags: [], forbids: [].}

Source Edit

  1. proc getCurrentException(): ref Exception {.compilerproc, inline, ...gcsafe,
  2. raises: [], tags: [], forbids: [].}

Retrieves the current exception; if there is none, nil is returned. Source Edit

  1. proc getCurrentExceptionMsg(): string {.inline, ...gcsafe, raises: [], tags: [],
  2. forbids: [].}

Retrieves the error message that was attached to the current exception; if there is none, “” is returned. Source Edit

  1. proc getFrame(): PFrame {.compilerproc, inline, ...raises: [], tags: [],
  2. forbids: [].}

Source Edit

  1. proc getFrameState(): FrameState {.compilerproc, inline, ...raises: [], tags: [],
  2. forbids: [].}

Source Edit

  1. 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

  1. 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

  1. proc getGcFrame(): GcFrame {.compilerproc, inline, ...raises: [], tags: [],
  2. forbids: [].}

Source Edit

  1. proc getMaxMem(): int {....raises: [], tags: [], forbids: [].}

Source Edit

  1. proc getOccupiedMem(): int {....gcsafe, raises: [], tags: [], forbids: [].}

Returns the number of bytes that are owned by the process and hold data. Source Edit

  1. 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

  1. proc getStackTrace(): string {....gcsafe, raises: [], tags: [], forbids: [].}

Gets the current stack trace. This only works for debug builds. Source Edit

  1. proc getStackTrace(e: ref Exception): string {....gcsafe, raises: [], tags: [],
  2. 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

  1. proc getStackTraceEntries(): seq[StackTraceEntry] {....raises: [], tags: [],
  2. forbids: [].}

Returns the stack trace entries for the current stack trace. This is not yet available for the JS backend. Source Edit

  1. proc getStackTraceEntries(e: ref Exception): lent seq[StackTraceEntry] {.
  2. ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc getTotalMem(): int {....gcsafe, raises: [], tags: [], forbids: [].}

Returns the number of bytes that are owned by the process. Source Edit

  1. 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

  1. proc getTypeInfo[T](x: T): pointer {.magic: "GetTypeInfo", ...gcsafe, raises: [],
  2. tags: [], forbids: [].}

Get type information for x.

Ordinary code should not use this, but the typeinfo module instead.

Source Edit

  1. proc gorge(command: string; input = ""; cache = ""): string {.
  2. magic: "StaticExec", ...raises: [], tags: [], forbids: [].}

This is an alias for staticExec. Source Edit

  1. proc gorgeEx(command: string; input = ""; cache = ""): tuple[output: string,
  2. exitCode: int] {....raises: [], tags: [], forbids: [].}

Similar to gorge but also returns the precious exit code. Source Edit

  1. proc high(T: typedesc[SomeFloat]): T:type

Source Edit

  1. proc high(x: cstring): int {.magic: "High", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Returns the highest possible index of a compatible string x. This is sometimes an O(n) operation.

See also:

Source Edit

  1. proc high(x: string): int {.magic: "High", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Returns the highest possible index of a string x.

  1. var str = "Hello world!"
  2. high(str) # => 11

See also:

Source Edit

  1. proc high[I, T](x: array[I, T]): I {.magic: "High", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Returns the highest possible index of an array x.

For empty arrays, the return type is int.

  1. var arr = [1, 2, 3, 4, 5, 6, 7]
  2. high(arr) # => 6
  3. for i in low(arr)..high(arr):
  4. echo arr[i]

See also:

Source Edit

  1. proc high[I, T](x: typedesc[array[I, T]]): I {.magic: "High", noSideEffect,
  2. ...raises: [], tags: [], forbids: [].}

Returns the highest possible index of an array type.

For empty arrays, the return type is int.

  1. high(array[7, int]) # => 6

See also:

Source Edit

  1. 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)`.",
  2. 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:

  1. high(2) # => 9223372036854775807

Source Edit

  1. proc high[T: Ordinal | enum | range](x: typedesc[T]): T {.magic: "High",
  2. 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.

  1. high(int) # => 9223372036854775807

See also:

Source Edit

  1. proc high[T](x: openArray[T]): int {.magic: "High", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Returns the highest possible index of a sequence x.

  1. var s = @[1, 2, 3, 4, 5, 6, 7]
  2. high(s) # => 6
  3. for i in low(s)..high(s):
  4. echo s[i]

See also:

Source Edit

  1. proc inc[T, V: Ordinal](x: var T; y: V = 1) {.magic: "Inc", noSideEffect,
  2. ...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:

  1. var i = 2
  2. inc(i)
  3. assert i == 3
  4. inc(i, 3)
  5. assert i == 6

Source Edit

  1. func incl[T](x: var set[T]; y: T) {.magic: "Incl", ...raises: [], tags: [],
  2. forbids: [].}

Includes element y in the set x.

This is the same as x = x + {y}, but it might be more efficient.

Example:

  1. var a = {1, 3, 5}
  2. a.incl(2)
  3. assert a == {1, 2, 3, 5}
  4. a.incl(4)
  5. assert a == {1, 2, 3, 4, 5}

Source Edit

  1. proc insert(x: var string; item: string; i = 0.Natural) {.noSideEffect,
  2. ...raises: [], tags: [], forbids: [].}

Inserts item into x at position i.

  1. var a = "abc"
  2. a.insert("zz", 0) # a <- "zzabc"

Source Edit

  1. proc insert[T](x: var seq[T]; item: sink T; i = 0.Natural) {.noSideEffect.}

Inserts item into x at position i.

  1. var i = @[1, 3, 5]
  2. i.insert(99, 0) # i <- @[99, 1, 3, 5]

Source Edit

  1. proc instantiationInfo(index = -1; fullPaths = false): tuple[filename: string,
  2. line: int, column: int] {.magic: "InstantiationInfo", noSideEffect,
  3. ...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:

  1. import std/strutils
  2. template testException(exception, code: untyped): typed =
  3. try:
  4. let pos = instantiationInfo()
  5. discard(code)
  6. echo "Test failure at $1:$2 with '$3'" % [pos.filename,
  7. $pos.line, astToStr(code)]
  8. assert false, "A test expecting failure succeeded?"
  9. except exception:
  10. discard
  11. proc tester(pos: int): int =
  12. let
  13. a = @[1, 2, 3]
  14. result = a[pos]
  15. when isMainModule:
  16. testException(IndexDefect, tester(30))
  17. testException(IndexDefect, tester(1))
  18. # --> Test failure at example.nim:20 with 'tester(1)'

Source Edit

  1. proc internalNew[T](a: var ref T) {.magic: "New", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Leaked implementation detail. Do not use. Source Edit

  1. proc `is`[T, S](x: T; y: S): bool {.magic: "Is", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Checks if T is of the same type as S.

For a negated version, use isnot.

  1. assert 42 is int
  2. assert @[1, 2] is seq
  3. proc test[T](a: T): int =
  4. when (T is int):
  5. return a
  6. else:
  7. return 0
  8. assert(test[int](3) == 3)
  9. assert(test[string]("xyz") == 0)

Source Edit

  1. proc isNil(x: cstring): bool {.noSideEffect, magic: "IsNil", ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc isNil(x: pointer): bool {.noSideEffect, magic: "IsNil", ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc isNil[T: proc | iterator {.closure.}](x: T): bool {.noSideEffect,
  2. magic: "IsNil", ...raises: [], tags: [], forbids: [].}

Fast check whether x is nil. This is sometimes more efficient than \== nil. Source Edit

  1. proc isNil[T](x: ptr T): bool {.noSideEffect, magic: "IsNil", ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc isNil[T](x: ref T): bool {.noSideEffect, magic: "IsNil", ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc isNotForeign(x: ForeignCell): bool {....raises: [], tags: [], forbids: [].}

returns true if ‘x’ belongs to the calling thread. No deep copy has to be performed then. Source Edit

  1. proc iterToProc(iter: typed; envType: typedesc; procName: untyped) {.
  2. magic: "Plugin", compileTime, ...raises: [], tags: [], forbids: [].}

Source Edit

  1. func len(x: (type array) | array): int {.magic: "LengthArray", ...raises: [],
  2. tags: [], forbids: [].}

Returns the length of an array or an array type. This is roughly the same as high(T)-low(T)+1.

Example:

  1. var a = [1, 1, 1]
  2. assert a.len == 3
  3. assert array[0, float].len == 0
  4. static: assert array[-2..2, float].len == 5

Source Edit

  1. proc len(x: cstring): int {.magic: "LengthStr", noSideEffect, ...raises: [],
  2. 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:

  1. doAssert len(cstring"abc") == 3
  2. doAssert len(cstring r"ab\0c") == 5 # \0 is escaped
  3. doAssert len(cstring"ab\0c") == 5 # ditto
  4. var a: cstring = "ab\0c"
  5. when defined(js): doAssert a.len == 4 # len ignores \0 for js
  6. else: doAssert a.len == 2 # \0 is a null terminator
  7. static:
  8. var a2: cstring = "ab\0c"
  9. doAssert a2.len == 2 # \0 is a null terminator, even in js vm

Source Edit

  1. func len(x: string): int {.magic: "LengthStr", ...raises: [], tags: [], forbids: [].}

Returns the length of a string.

Example:

  1. assert "abc".len == 3
  2. assert "".len == 0
  3. assert string.default.len == 0

Source Edit

  1. func len[T](x: seq[T]): int {.magic: "LengthSeq", ...raises: [], tags: [],
  2. forbids: [].}

Returns the length of x.

Example:

  1. assert @[0, 1].len == 2
  2. assert seq[int].default.len == 0
  3. assert newSeq[int](3).len == 3
  4. let s = newSeqOfCap[int](3)
  5. assert s.len == 0

Source Edit

  1. func len[T](x: set[T]): int {.magic: "Card", ...raises: [], tags: [], forbids: [].}

An alias for card(x). Source Edit

  1. func len[TOpenArray: openArray | varargs](x: TOpenArray): int {.
  2. magic: "LengthOpenArray", ...raises: [], tags: [], forbids: [].}

Returns the length of an openArray.

Example:

  1. proc bar[T](a: openArray[T]): int = len(a)
  2. assert bar([1,2]) == 2
  3. assert [1,2].len == 2

Source Edit

  1. 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.

  1. assert((0..5).len == 6)
  2. assert((5..2).len == 0)

Source Edit

  1. proc locals(): RootObj {.magic: "Plugin", noSideEffect, ...raises: [], tags: [],
  2. 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:

  1. proc testLocals() =
  2. var
  3. a = "something"
  4. b = 4
  5. c = locals()
  6. d = "super!"
  7. b = 1
  8. for name, value in fieldPairs(c):
  9. echo "name ", name, " with value ", value
  10. echo "B is ", b
  11. # -> name a with value something
  12. # -> name b with value 4
  13. # -> B is 1

Source Edit

  1. proc low(T: typedesc[SomeFloat]): T:type

Source Edit

  1. proc low(x: cstring): int {.magic: "Low", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Returns the lowest possible index of a compatible string x.

See also:

Source Edit

  1. proc low(x: string): int {.magic: "Low", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Returns the lowest possible index of a string x.

  1. var str = "Hello world!"
  2. low(str) # => 0

See also:

Source Edit

  1. proc low[I, T](x: array[I, T]): I {.magic: "Low", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Returns the lowest possible index of an array x.

For empty arrays, the return type is int.

  1. var arr = [1, 2, 3, 4, 5, 6, 7]
  2. low(arr) # => 0
  3. for i in low(arr)..high(arr):
  4. echo arr[i]

See also:

Source Edit

  1. proc low[I, T](x: typedesc[array[I, T]]): I {.magic: "Low", noSideEffect,
  2. ...raises: [], tags: [], forbids: [].}

Returns the lowest possible index of an array type.

For empty arrays, the return type is int.

  1. low(array[7, int]) # => 0

See also:

Source Edit

  1. 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)`.",
  2. 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:

  1. low(2) # => -9223372036854775808

Source Edit

  1. proc low[T: Ordinal | enum | range](x: typedesc[T]): T {.magic: "Low",
  2. 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.

  1. low(int) # => -9223372036854775808

See also:

Source Edit

  1. proc low[T](x: openArray[T]): int {.magic: "Low", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Returns the lowest possible index of a sequence x.

  1. var s = @[1, 2, 3, 4, 5, 6, 7]
  2. low(s) # => 0
  3. for i in low(s)..high(s):
  4. echo s[i]

See also:

Source Edit

  1. proc max(x, y: float32): float32 {.noSideEffect, inline, ...raises: [], tags: [],
  2. forbids: [].}

Source Edit

  1. proc max(x, y: float64): float64 {.noSideEffect, inline, ...raises: [], tags: [],
  2. forbids: [].}

Source Edit

  1. proc max(x, y: int): int {.magic: "MaxI", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Source Edit

  1. proc max(x, y: int8): int8 {.magic: "MaxI", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Source Edit

  1. proc max(x, y: int16): int16 {.magic: "MaxI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc max(x, y: int32): int32 {.magic: "MaxI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc max(x, y: int64): int64 {.magic: "MaxI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

The maximum value of two integers. Source Edit

  1. proc max[T: not SomeFloat](x, y: T): T {.inline.}

Generic maximum operator of 2 values based on <=. Source Edit

  1. proc max[T](x: openArray[T]): T

The maximum value of x. T needs to have a < operator. Source Edit

  1. proc min(x, y: float32): float32 {.noSideEffect, inline, ...raises: [], tags: [],
  2. forbids: [].}

Source Edit

  1. proc min(x, y: float64): float64 {.noSideEffect, inline, ...raises: [], tags: [],
  2. forbids: [].}

Source Edit

  1. proc min(x, y: int): int {.magic: "MinI", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Source Edit

  1. proc min(x, y: int8): int8 {.magic: "MinI", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Source Edit

  1. proc min(x, y: int16): int16 {.magic: "MinI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc min(x, y: int32): int32 {.magic: "MinI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc min(x, y: int64): int64 {.magic: "MinI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

The minimum value of two integers. Source Edit

  1. proc min[T: not SomeFloat](x, y: T): T {.inline.}

Generic minimum operator of 2 values based on <=. Source Edit

  1. proc min[T](x: openArray[T]): T

The minimum value of x. T needs to have a < operator. Source Edit

  1. proc `mod`(x, y: int): int {.magic: "ModI", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Computes the integer modulo operation (remainder).

This is the same as x - (x div y) * y.

Example:

  1. assert (7 mod 5) == 2
  2. assert (-7 mod 5) == -2
  3. assert (7 mod -5) == 2
  4. assert (-7 mod -5) == -2

Source Edit

  1. proc `mod`(x, y: int8): int8 {.magic: "ModI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `mod`(x, y: int16): int16 {.magic: "ModI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `mod`(x, y: int32): int32 {.magic: "ModI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `mod`(x, y: int64): int64 {.magic: "ModI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `mod`(x, y: uint): uint {.magic: "ModU", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Computes the integer modulo operation (remainder) for unsigned integers. This is the same as x - (x div y) * y. Source Edit

  1. proc `mod`(x, y: uint8): uint8 {.magic: "ModU", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `mod`(x, y: uint16): uint16 {.magic: "ModU", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `mod`(x, y: uint32): uint32 {.magic: "ModU", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `mod`(x, y: uint64): uint64 {.magic: "ModU", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc move[T](x: var T): T {.magic: "Move", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Source Edit

  1. proc moveMem(dest, source: pointer; size: Natural) {.inline, ...gcsafe, tags: [],
  2. 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

  1. 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

  1. proc new[T](a: var ref T) {.magic: "New", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Creates a new object of type T and returns a safe (traced) reference to it in a. Source Edit

  1. proc new[T](a: var ref T; finalizer: proc (x: ref T) {.nimcall.}) {.
  2. 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

  1. 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.

  1. var inputStrings = newSeq[string](3)
  2. assert len(inputStrings) == 3
  3. inputStrings[0] = "The fourth"
  4. inputStrings[1] = "assignment"
  5. inputStrings[2] = "would crash"
  6. #inputStrings[3] = "out of bounds"

See also:

Source Edit

  1. proc newSeq[T](s: var seq[T]; len: Natural) {.magic: "NewSeq", noSideEffect,
  2. ...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:

  1. var inputStrings: seq[string]
  2. newSeq(inputStrings, 3)
  3. assert len(inputStrings) == 3
  4. inputStrings[0] = "The fourth"
  5. inputStrings[1] = "assignment"
  6. inputStrings[2] = "would crash"
  7. #inputStrings[3] = "out of bounds"

Source Edit

  1. proc newSeqOfCap[T](cap: Natural): seq[T] {.magic: "NewSeqOfCap", noSideEffect,
  2. ...raises: [], tags: [], forbids: [].}

Creates a new sequence of type seq[T] with length zero and capacity cap. Example:

  1. var x = newSeqOfCap[int](5)
  2. assert len(x) == 0
  3. x.add(10)
  4. assert len(x) == 1

Source Edit

  1. proc newSeqUninitialized[T: SomeNumber](len: Natural): seq[T]

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:

  1. var x = newSeqUninitialized[int](3)
  2. assert len(x) == 3
  3. x[0] = 10

Source Edit

  1. proc newString(len: Natural): string {.magic: "NewString",
  2. importc: "mnewString", noSideEffect,
  3. ...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

  1. proc newStringOfCap(cap: Natural): string {.magic: "NewStringOfCap",
  2. 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

  1. proc nimGC_setStackBottom(theStackBottom: pointer) {.compilerproc, noinline,
  2. ...gcsafe, raises: [], tags: [], forbids: [].}

Expands operating GC stack range to theStackBottom. Does nothing if current stack bottom is already lower than theStackBottom. Source Edit

  1. proc `not`(a: typedesc): typedesc {.magic: "TypeTrait", noSideEffect,
  2. ...raises: [], tags: [], forbids: [].}

Constructs an not meta class. Source Edit

  1. proc `not`(x: bool): bool {.magic: "Not", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Boolean not; returns true if x == false. Source Edit

  1. proc `not`(x: int): int {.magic: "BitnotI", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Computes the bitwise complement of the integer x.

Example:

  1. assert not 0'u8 == 255
  2. assert not 0'i8 == -1
  3. assert not 1000'u16 == 64535
  4. assert not 1000'i16 == -1001

Source Edit

  1. proc `not`(x: int8): int8 {.magic: "BitnotI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `not`(x: int16): int16 {.magic: "BitnotI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `not`(x: int32): int32 {.magic: "BitnotI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `not`(x: int64): int64 {.magic: "BitnotI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `not`(x: uint): uint {.magic: "BitnotI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Computes the bitwise complement of the integer x. Source Edit

  1. proc `not`(x: uint8): uint8 {.magic: "BitnotI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `not`(x: uint16): uint16 {.magic: "BitnotI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `not`(x: uint32): uint32 {.magic: "BitnotI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `not`(x: uint64): uint64 {.magic: "BitnotI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `of`[T, S](x: T; y: typedesc[S]): bool {.magic: "Of", noSideEffect,
  2. ...raises: [], tags: [], forbids: [].}

Checks if x is an instance of y.

Example:

  1. type
  2. Base = ref object of RootObj
  3. Sub1 = ref object of Base
  4. Sub2 = ref object of Base
  5. Unrelated = ref object
  6. var base: Base = Sub1() # downcast
  7. doAssert base of Base # generates `CondTrue` (statically true)
  8. doAssert base of Sub1
  9. doAssert base isnot Sub1
  10. doAssert not (base of Sub2)
  11. base = Sub2() # re-assign
  12. doAssert base of Sub2
  13. doAssert Sub2(base) != nil # upcast
  14. doAssertRaises(ObjectConversionDefect): discard Sub1(base)
  15. var sub1 = Sub1()
  16. doAssert sub1 of Base
  17. doAssert sub1.Base of Sub1
  18. doAssert not compiles(base of Unrelated)

Source Edit

  1. proc onThreadDestruction(handler: proc () {.closure, ...gcsafe, raises: [].}) {.
  2. ...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

  1. 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.

Source Edit

  1. proc `or`(a, b: typedesc): typedesc {.magic: "TypeTrait", noSideEffect,
  2. ...raises: [], tags: [], forbids: [].}

Constructs an or meta class. Source Edit

  1. proc `or`(x, y: bool): bool {.magic: "Or", noSideEffect, ...raises: [], tags: [],
  2. 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

  1. proc `or`(x, y: int): int {.magic: "BitorI", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Computes the bitwise or of numbers x and y.

Example:

  1. assert (0b0011 or 0b0101) == 0b0111
  2. assert (0b0111 or 0b1100) == 0b1111

Source Edit

  1. proc `or`(x, y: int8): int8 {.magic: "BitorI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `or`(x, y: int16): int16 {.magic: "BitorI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `or`(x, y: int32): int32 {.magic: "BitorI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `or`(x, y: int64): int64 {.magic: "BitorI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `or`(x, y: uint): uint {.magic: "BitorI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Computes the bitwise or of numbers x and y. Source Edit

  1. proc `or`(x, y: uint8): uint8 {.magic: "BitorI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `or`(x, y: uint16): uint16 {.magic: "BitorI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `or`(x, y: uint32): uint32 {.magic: "BitorI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `or`(x, y: uint64): uint64 {.magic: "BitorI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. func ord[T: Ordinal | enum](x: T): int {.magic: "Ord", ...raises: [], tags: [],
  2. forbids: [].}

Returns the internal int value of x, including for enum with holes and distinct ordinal types.

Example:

  1. assert ord('A') == 65
  2. type Foo = enum
  3. f0 = 0, f1 = 3
  4. assert f1.ord == 3
  5. type Bar = distinct int
  6. assert 3.Bar.ord == 3

Source Edit

  1. 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.

Source Edit

  1. 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:

  1. var a = @[1, 3, 5, 7]
  2. let b = pop(a)
  3. assert b == 7
  4. assert a == @[1, 3, 5]

Source Edit

  1. proc popGcFrame() {.compilerproc, inline, ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc pred[T, V: Ordinal](x: T; y: V = 1): T {.magic: "Pred", noSideEffect,
  2. ...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:

  1. assert pred(5) == 4
  2. assert pred(5, 3) == 2

Source Edit

  1. proc prepareMutation(s: var string) {.inline, ...raises: [], tags: [], forbids: [].}

String literals (e.g. “abc”, etc) in the ARC/ORC mode are “copy on write”, therefore you should call prepareMutation before modifying the strings via addr.

Example:

  1. var x = "abc"
  2. var y = "defgh"
  3. prepareMutation(y) # without this, you may get a `SIGBUS` or `SIGSEGV`
  4. moveMem(addr y[0], addr x[0], x.len)
  5. assert y == "abcgh"

Source Edit

  1. proc procCall(x: untyped) {.magic: "ProcCall", compileTime, ...raises: [],
  2. tags: [], forbids: [].}

Special magic to prohibit dynamic binding for method calls. This is similar to super in ordinary OO languages.

  1. # 'someMethod' will be resolved fully statically:
  2. procCall someMethod(a, b)

Source Edit

  1. proc protect(x: pointer): ForeignCell {....raises: [], tags: [], forbids: [].}

Source Edit

  1. proc pushGcFrame(s: GcFrame) {.compilerproc, inline, ...raises: [], tags: [],
  2. forbids: [].}

Source Edit

  1. proc quit(errorcode: int = QuitSuccess) {.magic: "Exit", noreturn, ...raises: [],
  2. 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. doAssert false 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

  1. proc quit(errormsg: string; errorcode = QuitFailure) {.noreturn, ...raises: [],
  2. tags: [], forbids: [].}

A shorthand for echo(errormsg); quit(errorcode). Source Edit

  1. proc rawEnv[T: proc {.closure.} | iterator {.closure.}](x: T): pointer {.
  2. noSideEffect, inline.}

Retrieves the raw environment pointer of the closure x. See also rawProc. Source Edit

  1. proc rawProc[T: proc {.closure.} | iterator {.closure.}](x: T): pointer {.
  2. noSideEffect, inline.}

Retrieves the raw proc pointer of the closure x. This is useful for interfacing closures with C/C++, hash compuations, etc. Source Edit

  1. proc ready[TMsg](c: var Channel[TMsg]): bool

Returns true if some thread is waiting on the channel c for new messages. Source Edit

  1. proc realloc0Impl(p: pointer; oldSize, newSize: Natural): pointer {.noconv,
  2. ...gcsafe, tags: [], gcsafe, raises: [], forbids: [].}

Source Edit

  1. proc reallocImpl(p: pointer; newSize: Natural): pointer {.noconv, ...gcsafe,
  2. tags: [], gcsafe, raises: [], forbids: [].}

Source Edit

  1. proc reallocShared0Impl(p: pointer; oldSize, newSize: Natural): pointer {.
  2. noconv, ...gcsafe, tags: [], gcsafe, raises: [], forbids: [].}

Source Edit

  1. proc reallocSharedImpl(p: pointer; newSize: Natural): pointer {.noconv, ...gcsafe,
  2. tags: [], gcsafe, raises: [], forbids: [].}

Source Edit

  1. 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.

Source Edit

  1. proc repr[T, U](x: HSlice[T, U]): string

Generic repr operator for slices that is lifted from the components of x. Example:

  1. $(1 .. 5) == "1 .. 5"

Source Edit

  1. proc repr[T](x: T): string {.magic: "Repr", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Takes any Nim variable and returns its string representation. No trailing newline is inserted (so echo won’t add an empty newline). Use -d:nimLegacyReprWithNewline to revert to old behavior where newlines were added in some cases.

It works even for complex data graphs with cycles. This is a great debugging tool.

  1. var s: seq[string] = @["test2", "test2"]
  2. var i = @[1, 2, 3, 4, 5]
  3. echo repr(s) # => 0x1055eb050[0x1055ec050"test2", 0x1055ec078"test2"]
  4. echo repr(i) # => 0x1055ed050[1, 2, 3, 4, 5]

Source Edit

  1. proc reprDiscriminant(e: int; typ: PNimType): string {.compilerproc, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc reset[T](obj: var T) {.noSideEffect.}

Resets an object obj to its default value. Source Edit

  1. 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

  1. 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

  1. proc runnableExamples(rdoccmd = ""; body: untyped) {.magic: "RunnableExamples",
  2. ...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:

  1. proc timesTwo*(x: int): int =
  2. ## This proc doubles a number.
  3. runnableExamples:
  4. # at module scope
  5. const exported* = 123
  6. assert timesTwo(5) == 10
  7. block: # at block scope
  8. defer: echo "done"
  9. runnableExamples "-d:foo -b:cpp":
  10. import std/compilesettings
  11. assert querySetting(backend) == "cpp"
  12. assert defined(foo)
  13. runnableExamples "-r:off": ## this one is only compiled
  14. import std/browsers
  15. openDefaultBrowser "https://forum.nim-lang.org/"
  16. 2 * x

Source Edit

  1. proc send[TMsg](c: var Channel[TMsg]; msg: sink TMsg) {.inline.}

Sends a message to a thread. msg is deeply copied. Source Edit

  1. proc setControlCHook(hook: proc () {.noconv.}) {....raises: [], tags: [],
  2. forbids: [].}

Allows you to override the behaviour of your application when CTRL+C is pressed. Only one such hook is supported. Example:

  1. proc ctrlc() {.noconv.} =
  2. echo "Ctrl+C fired!"
  3. # do clean up stuff
  4. quit()
  5. setControlCHook(ctrlc)

Source Edit

  1. proc setCurrentException(exc: ref Exception) {.inline, ...gcsafe, raises: [],
  2. tags: [], forbids: [].}

Sets the current exception.

Warning: Only use this if you know what you are doing.

Source Edit

  1. proc setFrame(s: PFrame) {.compilerproc, inline, ...raises: [], tags: [],
  2. forbids: [].}

Source Edit

  1. proc setFrameState(state: FrameState) {.compilerproc, inline, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc setGcFrame(s: GcFrame) {.compilerproc, inline, ...raises: [], tags: [],
  2. forbids: [].}

Source Edit

  1. proc setLen(s: var string; newlen: Natural) {.magic: "SetLengthStr",
  2. 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.

  1. var myS = "Nim is great!!"
  2. myS.setLen(3) # myS <- "Nim"
  3. echo myS, " is fantastic!!"

Source Edit

  1. proc setLen[T](s: var seq[T]; newlen: Natural) {.magic: "SetLengthSeq",
  2. 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.

  1. var x = @[10, 20]
  2. x.setLen(5)
  3. x[4] = 50
  4. assert x == @[10, 20, 0, 0, 50]
  5. x.setLen(1)
  6. assert x == @[10]

Source Edit

  1. proc setupForeignThreadGc() {....gcsafe, raises: [], tags: [], forbids: [].}

Call this if you registered a callback that will be run from a thread not under your control. This has a cheap thread-local guard, so the GC for this thread will only be initialized once per thread, no matter how often it is called.

This function is available only when --threads:on and --tlsEmulation:off switches are used

Source Edit

  1. proc shallow(s: var string) {.noSideEffect, inline, ...raises: [], tags: [],
  2. forbids: [].}

Marks a string s as shallow. Subsequent assignments will not perform deep copies of s.

This is only useful for optimization purposes.

Source Edit

  1. proc shallow[T](s: var seq[T]) {.noSideEffect, inline.}

Marks a sequence s as shallow. Subsequent assignments will not perform deep copies of s.

This is only useful for optimization purposes.

Source Edit

  1. proc shallowCopy[T](x: var T; y: T) {.noSideEffect, magic: "ShallowCopy",
  2. ...raises: [], tags: [], forbids: [].}

Use this instead of \= for a shallow copy.

The shallow copy only changes the semantics for sequences and strings (and types which contain those).

Be careful with the changed semantics though! There is a reason why the default assignment does a deep copy of sequences and strings.

Source Edit

  1. proc `shl`(x: int8; y: SomeInteger): int8 {.magic: "ShlI", noSideEffect,
  2. ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `shl`(x: int16; y: SomeInteger): int16 {.magic: "ShlI", noSideEffect,
  2. ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `shl`(x: int32; y: SomeInteger): int32 {.magic: "ShlI", noSideEffect,
  2. ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `shl`(x: int64; y: SomeInteger): int64 {.magic: "ShlI", noSideEffect,
  2. ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `shl`(x: int; y: SomeInteger): int {.magic: "ShlI", noSideEffect,
  2. ...raises: [], tags: [], forbids: [].}

Computes the shift left operation of x and y.

Note: Operator precedence is different than in C.

Example:

  1. assert 1'i32 shl 4 == 0x0000_0010
  2. assert 1'i64 shl 4 == 0x0000_0000_0000_0010

Source Edit

  1. proc `shl`(x: uint8; y: SomeInteger): uint8 {.magic: "ShlI", noSideEffect,
  2. ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `shl`(x: uint16; y: SomeInteger): uint16 {.magic: "ShlI", noSideEffect,
  2. ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `shl`(x: uint32; y: SomeInteger): uint32 {.magic: "ShlI", noSideEffect,
  2. ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `shl`(x: uint64; y: SomeInteger): uint64 {.magic: "ShlI", noSideEffect,
  2. ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `shl`(x: uint; y: SomeInteger): uint {.magic: "ShlI", noSideEffect,
  2. ...raises: [], tags: [], forbids: [].}

Computes the shift left operation of x and y. Source Edit

  1. proc `shr`(x: int8; y: SomeInteger): int8 {.magic: "AshrI", noSideEffect,
  2. ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `shr`(x: int16; y: SomeInteger): int16 {.magic: "AshrI", noSideEffect,
  2. ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `shr`(x: int32; y: SomeInteger): int32 {.magic: "AshrI", noSideEffect,
  2. ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `shr`(x: int64; y: SomeInteger): int64 {.magic: "AshrI", noSideEffect,
  2. ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `shr`(x: int; y: SomeInteger): int {.magic: "AshrI", noSideEffect,
  2. ...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:

  1. assert 0b0001_0000'i8 shr 2 == 0b0000_0100'i8
  2. assert 0b0000_0001'i8 shr 1 == 0b0000_0000'i8
  3. assert 0b1000_0000'i8 shr 4 == 0b1111_1000'i8
  4. assert -1 shr 5 == -1
  5. assert 1 shr 5 == 0
  6. assert 16 shr 2 == 4
  7. assert -16 shr 2 == -4

Source Edit

  1. proc `shr`(x: uint8; y: SomeInteger): uint8 {.magic: "ShrI", noSideEffect,
  2. ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `shr`(x: uint16; y: SomeInteger): uint16 {.magic: "ShrI", noSideEffect,
  2. ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `shr`(x: uint32; y: SomeInteger): uint32 {.magic: "ShrI", noSideEffect,
  2. ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `shr`(x: uint64; y: SomeInteger): uint64 {.magic: "ShrI", noSideEffect,
  2. ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc `shr`(x: uint; y: SomeInteger): uint {.magic: "ShrI", noSideEffect,
  2. ...raises: [], tags: [], forbids: [].}

Computes the shift right operation of x and y. Source Edit

  1. proc sizeof(x: typedesc): int {.magic: "SizeOf", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc sizeof[T](x: T): int {.magic: "SizeOf", noSideEffect, ...raises: [], tags: [],
  2. 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.

  1. sizeof('A') # => 1
  2. sizeof(2) # => 8

Source Edit

  1. proc slurp(filename: string): string {.magic: "Slurp", ...raises: [], tags: [],
  2. forbids: [].}

This is an alias for staticRead. Source Edit

  1. proc stackTraceAvailable(): bool {....raises: [], tags: [], forbids: [].}

Source Edit

  1. proc staticExec(command: string; input = ""; cache = ""): string {.
  2. 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.

  1. const buildInfo = "Revision " & staticExec("git rev-parse HEAD") &
  2. "\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:

  1. const stateMachine = staticExec("dfaoptimizer", "input", "0.8.0")

Source Edit

  1. proc staticRead(filename: string): string {.magic: "Slurp", ...raises: [],
  2. 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.

  1. const myResource = staticRead"mydatafile.bin"

slurp is an alias for staticRead.

Source Edit

  1. proc substr(s: openArray[char]): string {....raises: [], tags: [], forbids: [].}

Copies a slice of s into a new string and returns this new string.

Example:

  1. let a = "abcdefgh"
  2. assert a.substr(2, 5) == "cdef"
  3. assert a.substr(2) == "cdefgh"
  4. assert a.substr(5, 99) == "fgh"

Source Edit

  1. proc substr(s: string; first = 0): string {....raises: [], tags: [], forbids: [].}

Source Edit

  1. proc substr(s: string; first, last: int): string {....raises: [], tags: [],
  2. 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:

  1. let a = "abcdefgh"
  2. assert a.substr(2, 5) == "cdef"
  3. assert a.substr(2) == "cdefgh"
  4. assert a.substr(5, 99) == "fgh"

Source Edit

  1. proc succ[T, V: Ordinal](x: T; y: V = 1): T {.magic: "Succ", noSideEffect,
  2. ...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:

  1. assert succ(5) == 6
  2. assert succ(5, 3) == 8

Source Edit

  1. proc swap[T](a, b: var T) {.magic: "Swap", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Swaps the values a and b.

This is often more efficient than tmp = a; a = b; b = tmp. Particularly useful for sorting algorithms.

  1. var
  2. a = 5
  3. b = 9
  4. swap(a, b)
  5. assert a == 9
  6. assert b == 5

Source Edit

  1. proc tearDownForeignThreadGc() {....gcsafe, raises: [], tags: [], forbids: [].}

Call this to tear down the GC, previously initialized by setupForeignThreadGc. If GC has not been previously initialized, or has already been torn down, the call does nothing.

This function is available only when --threads:on and --tlsEmulation:off switches are used

Source Edit

  1. proc toBiggestFloat(i: BiggestInt): BiggestFloat {.noSideEffect, inline,
  2. ...raises: [], tags: [], forbids: [].}

Same as toFloat but for BiggestInt to BiggestFloat. Source Edit

  1. proc toBiggestInt(f: BiggestFloat): BiggestInt {.noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Same as toInt but for BiggestFloat to BiggestInt. Source Edit

  1. proc toFloat(i: int): float {.noSideEffect, inline, ...raises: [], tags: [],
  2. 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.

  1. let
  2. a = 2
  3. b = 3.7
  4. echo a.toFloat + b # => 5.7

Source Edit

  1. 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.

  1. doAssert toInt(0.49) == 0
  2. doAssert toInt(0.5) == 1
  3. doAssert toInt(-0.5) == -1 # rounding is symmetrical

Source Edit

  1. proc toOpenArray(x: cstring; first, last: int): openArray[char] {.
  2. magic: "Slice", ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc toOpenArray(x: string; first, last: int): openArray[char] {.magic: "Slice",
  2. ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc toOpenArray[I, T](x: array[I, T]; first, last: I): openArray[T] {.
  2. magic: "Slice", ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc toOpenArray[T](x: openArray[T]; first, last: int): openArray[T] {.
  2. magic: "Slice", ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc toOpenArray[T](x: ptr UncheckedArray[T]; first, last: int): openArray[T] {.
  2. magic: "Slice", ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc toOpenArray[T](x: seq[T]; first, last: int): openArray[T] {.magic: "Slice",
  2. ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc toOpenArrayByte(x: cstring; first, last: int): openArray[byte] {.
  2. magic: "Slice", ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc toOpenArrayByte(x: openArray[char]; first, last: int): openArray[byte] {.
  2. magic: "Slice", ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc toOpenArrayByte(x: seq[char]; first, last: int): openArray[byte] {.
  2. magic: "Slice", ...raises: [], tags: [], forbids: [].}

Source Edit

  1. proc toOpenArrayByte(x: string; first, last: int): openArray[byte] {.
  2. magic: "Slice", ...raises: [], tags: [], forbids: [].}

Source Edit

  1. 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).

Source Edit

  1. 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.

Source Edit

  1. proc typeof(x: untyped; mode = typeOfIter): typedesc {.magic: "TypeOf",
  2. noSideEffect, compileTime, ...raises: [], tags: [], forbids: [].}

Builtin typeof operation for accessing the type of an expression. Since version 0.20.0.

Example:

  1. proc myFoo(): float = 0.0
  2. iterator myFoo(): string = yield "abc"
  3. iterator myFoo2(): string = yield "abc"
  4. iterator myFoo3(): string {.closure.} = yield "abc"
  5. doAssert type(myFoo()) is string
  6. doAssert typeof(myFoo()) is string
  7. doAssert typeof(myFoo(), typeOfIter) is string
  8. doAssert typeof(myFoo3) is iterator
  9. doAssert typeof(myFoo(), typeOfProc) is float
  10. doAssert typeof(0.0, typeOfProc) is float
  11. doAssert typeof(myFoo3, typeOfProc) is iterator
  12. doAssert not compiles(typeof(myFoo2(), typeOfProc))
  13. # this would give: Error: attempting to call routine: 'myFoo2'
  14. # since `typeOfProc` expects a typed expression and `myFoo2()` can
  15. # only be used in a `for` context.

Source Edit

  1. proc unsafeAddr[T](x: T): ptr T {.magic: "Addr", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Warning: unsafeAddr is a deprecated alias for addr, use addr instead.

Source Edit

  1. proc unsafeNew[T](a: var ref T; size: Natural) {.magic: "New", noSideEffect,
  2. ...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

  1. proc unsetControlCHook() {....raises: [], tags: [], forbids: [].}

Reverts a call to setControlCHook. Source Edit

  1. 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

  1. 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

  1. proc `xor`(x, y: bool): bool {.magic: "Xor", noSideEffect, ...raises: [], tags: [],
  2. forbids: [].}

Boolean exclusive or; returns true if x != y (if either argument is true while the other is false). Source Edit

  1. proc `xor`(x, y: int): int {.magic: "BitxorI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Computes the bitwise xor of numbers x and y.

Example:

  1. assert (0b0011 xor 0b0101) == 0b0110
  2. assert (0b0111 xor 0b1100) == 0b1011

Source Edit

  1. proc `xor`(x, y: int8): int8 {.magic: "BitxorI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `xor`(x, y: int16): int16 {.magic: "BitxorI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `xor`(x, y: int32): int32 {.magic: "BitxorI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `xor`(x, y: int64): int64 {.magic: "BitxorI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `xor`(x, y: uint): uint {.magic: "BitxorI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Computes the bitwise xor of numbers x and y. Source Edit

  1. proc `xor`(x, y: uint8): uint8 {.magic: "BitxorI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `xor`(x, y: uint16): uint16 {.magic: "BitxorI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `xor`(x, y: uint32): uint32 {.magic: "BitxorI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc `xor`(x, y: uint64): uint64 {.magic: "BitxorI", noSideEffect, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. func zeroDefault[T](_: typedesc[T]): T {.magic: "ZeroDefault", ...raises: [],
  2. tags: [], forbids: [].}

Returns the binary zeros representation of the type T. It ignores default fields of an object.

See also:

Source Edit

  1. proc zeroMem(p: pointer; size: Natural) {.inline, noSideEffect, ...tags: [],
  2. 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

  1. proc `|`(a, b: typedesc): typedesc

Source Edit

Iterators

  1. 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

  1. 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

  1. 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

  1. 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

  1. iterator `..`[T](a, b: T): T {.inline.}

An alias for countup(a, b, 1).

See also:

Example:

  1. import std/sugar
  2. let x = collect(newSeq):
  3. for i in 3 .. 7:
  4. i
  5. assert x == @[3, 4, 5, 6, 7]

Source Edit

  1. 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

  1. 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

  1. 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

  1. 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

  1. iterator `..<`[T](a, b: T): T {.inline.}

Source Edit

  1. 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:

  1. import std/sugar
  2. let x = collect(newSeq):
  3. for i in countdown(7, 3):
  4. i
  5. assert x == @[7, 6, 5, 4, 3]
  6. let y = collect(newseq):
  7. for i in countdown(9, 2, 3):
  8. i
  9. assert y == @[9, 6, 3]

Source Edit

  1. 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:

  1. import std/sugar
  2. let x = collect(newSeq):
  3. for i in countup(3, 7):
  4. i
  5. assert x == @[3, 4, 5, 6, 7]
  6. let y = collect(newseq):
  7. for i in countup(2, 9, 3):
  8. i
  9. assert y == @[2, 5, 8]

Source Edit

  1. iterator `||`[S, T](a: S; b: T; annotation: static string = "parallel for"): T {.
  2. 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

  1. iterator `||`[S, T](a: S; b: T; step: Positive;
  2. annotation: static string = "parallel for"): T {.inline,
  3. 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

  1. macro varargsLen(x: varargs[untyped]): int

returns number of variadic arguments in x Source Edit

Templates

  1. template `!=`(x, y: untyped): untyped {.callsite.}

Unequals operator. This is a shorthand for not (x == y). Source Edit

  1. template `&=`(x, y: typed)

Generic ‘sink’ operator for Nim.

If not specialized further, an alias for add.

Source Edit

  1. template `..<`(a, b: untyped): untyped

A shortcut for a .. pred(b).

  1. for i in 5 ..< 9:
  2. echo i # => 5; 6; 7; 8

Source Edit

  1. template `..^`(a, b: untyped): untyped

A shortcut for .. ^ to avoid the common gotcha that a space between ‘..’ and ‘^’ is required. Source Edit

  1. template `>`(x, y: untyped): untyped {.callsite.}

“is greater” operator. This is the same as y < x. Source Edit

  1. template `>%`(x, y: untyped): untyped

Treats x and y as unsigned and compares them. Returns true if unsigned(x) > unsigned(y). Source Edit

  1. template `>=`(x, y: untyped): untyped {.callsite.}

“is greater or equals” operator. This is the same as y <= x. Source Edit

  1. template `>=%`(x, y: untyped): untyped

Treats x and y as unsigned and compares them. Returns true if unsigned(x) >= unsigned(y). Source Edit

  1. template `[]`(s: string; i: int): char

Source Edit

  1. template `[]=`(s: string; i: int; val: char)

Source Edit

  1. 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].

  1. let
  2. a = [1, 3, 5, 7, 9]
  3. b = "abcdefgh"
  4. echo a[^1] # => 9
  5. echo b[^2] # => g

Source Edit

  1. 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

  1. 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

  1. 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

  1. 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

  1. 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:

  1. var myClosure : proc()
  2. # without closureScope:
  3. for i in 0 .. 5:
  4. let j = i
  5. if j == 3:
  6. myClosure = proc() = echo j
  7. myClosure() # outputs 5. `j` is changed after closure creation
  8. # with closureScope:
  9. for i in 0 .. 5:
  10. closureScope: # Everything in this scope is locked after closure creation
  11. let j = i
  12. if j == 3:
  13. myClosure = proc() = echo j
  14. myClosure() # outputs 3

Source Edit

  1. 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

  1. 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

  1. template dumpAllocstats(code: untyped)

Source Edit

  1. template excl[T](x: var set[T]; y: set[T]) {.callsite.}

Excludes the set y from the set x.

Example:

  1. var a = {1, 3, 5, 7}
  2. var b = {3, 4, 5}
  3. a.excl(b)
  4. assert a == {1, 7}

Source Edit

  1. template formatErrorIndexBound[T](i, a, b: T): string

Source Edit

  1. template formatErrorIndexBound[T](i, n: T): string

Source Edit

  1. template formatFieldDefect(f, discVal): string

Source Edit

  1. template `in`(x, y: untyped): untyped {.dirty, callsite.}

Sugar for contains.

  1. assert(1 in (1..3) == true)
  2. assert(5 in (1..3) == false)

Source Edit

  1. template incl[T](x: var set[T]; y: set[T]) {.callsite.}

Includes the set y in the set x.

Example:

  1. var a = {1, 3, 5, 7}
  2. var b = {4, 5, 6}
  3. a.incl(b)
  4. assert a == {1, 3, 4, 5, 6, 7}

Source Edit

  1. template `isnot`(x, y: untyped): untyped {.callsite.}

Negated version of is. Equivalent to not(x is y).

  1. assert 42 isnot float
  2. assert @[1, 2] isnot enum

Source Edit

  1. 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:

  1. for value in inputValues:
  2. if likely(value <= 100):
  3. process(value)
  4. else:
  5. echo "Value too big!"

On backends without branch prediction (JS and the nimscript VM), this template will not affect code execution.

Source Edit

  1. template newException(exceptn: typedesc; message: string;
  2. 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

  1. template nimThreadProcWrapperBody(closure: untyped): untyped

Source Edit

  1. template `notin`(x, y: untyped): untyped {.dirty, callsite.}

Sugar for not contains.

  1. assert(1 notin (1..3) == false)
  2. assert(5 notin (1..3) == true)

Source Edit

  1. template offsetOf[T](t: typedesc[T]; member: untyped): int

Source Edit

  1. template offsetOf[T](value: T; member: untyped): int

Source Edit

  1. template once(body: untyped): untyped

Executes a block of code only once (the first time the block is reached).

  1. proc draw(t: Triangle) =
  2. once:
  3. graphicsInit()
  4. line(t.p1, t.p2)
  5. line(t.p2, t.p3)
  6. line(t.p3, t.p1)

Source Edit

  1. 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

  1. 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

  1. 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

  1. 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

  1. 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

  1. 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:

  1. for value in inputValues:
  2. if unlikely(value > 100):
  3. echo "Value too big!"
  4. else:
  5. process(value)

On backends without branch prediction (JS and the nimscript VM), this template will not affect code execution.

Source Edit

  1. template unown(x: typed): untyped

Source Edit

Exports

FloatOverflowDefect, ResourceExhaustedError, NilAccessError, FloatUnderflowDefect, RangeDefect, IndexDefect, FloatUnderflowError, FloatOverflowError, FloatDivByZeroDefect, FloatInvalidOpError, FloatingPointError, DivByZeroError, OutOfMemError, RangeError, IndexError, ReraiseError, IOError, DeadThreadError, WriteIOEffect, FloatDivByZeroError, ExecIOEffect, IOEffect, ReraiseDefect, ValueError, OverflowDefect, ReadIOEffect, ObjectConversionDefect, AccessViolationDefect, KeyError, ObjectAssignmentDefect, OverflowError, ArithmeticError, ArithmeticDefect, AccessViolationError, EOFError, FieldDefect, ObjectAssignmentError, StackOverflowDefect, NilAccessDefect, ObjectConversionError, FloatInexactError, FloatingPointDefect, TimeEffect, LibraryError, OSError, OutOfMemDefect, DivByZeroDefect, FloatInexactDefect, StackOverflowError, AssertionError, AssertionDefect, FieldError, DeadThreadDefect, FloatInvalidOpDefect, BiggestUInt, BiggestInt, cfloat, cushort, csize_t, culonglong, cuint, cshort, clonglong, clong, cuchar, PFloat64, PInt64, PInt32, culong, cschar, BiggestFloat, cstringArray, cchar, cdouble, clongdouble, cint, ByteAddress, PFloat32, atomicTestAndSet, atomicAddFetch, atomicLoadN, atomicAndFetch, atomicAlwaysLockFree, atomicXorFetch, AtomMemModel, atomicFetchAnd, atomicLoad, atomicExchange, atomicCompareExchangeN, ATOMIC_ACQUIRE, atomicSignalFence, atomicFetchAdd, cas, atomicFetchNand, cpuRelax, atomicInc, atomicOrFetch, atomicFetchSub, ATOMIC_ACQ_REL, atomicFetchXor, atomicCompareExchange, ATOMIC_RELEASE, ATOMIC_RELAXED, ATOMIC_SEQ_CST, atomicIsLockFree, atomicClear, atomicStoreN, ATOMIC_CONSUME, atomicSubFetch, atomicDec, atomicNandFetch, AtomType, atomicStore, atomicFetchOr, atomicThreadFence, fence, atomicExchangeN, doAssertRaises, raiseAssert, failedAssertImpl, doAssert, assert, onFailedAssert, items, mpairs, items, fieldPairs, items, pairs, fieldPairs, mitems, fields, mpairs, pairs, mitems, items, items, fields, mitems, items, mpairs, mpairs, items, mpairs, pairs, pairs, items, mitems, items, pairs, mitems, $, $, $, $, $, $, addFloat, $, $, $, $, $, $, $, $, $, $, $, $, $, $, getThreadId, createThread), handle, running, joinThread, createThread,TArg), joinThreads, Thread, pinToCpu, addInt, addInt, addInt, len, $, newWideCString, WideCStringObj, Utf16Char, $, newWideCString, newWideCString, WideCString, newWideCString, writeFile, write, File, write, writeChars, endOfFile, getFilePos, &=, readChars, write, readLine, open, writeFile, write, readChar, writeBuffer, readBytes, getFileHandle, close, write, getOsFileHandle, readFile, setFilePos, write, setStdIoUnbuffered, readChars, lines, stdout, readLines, getFileSize, FileHandle, write, reopen, stdmsg, writeLine, write, setInheritable, readLine, open, flushFile, readLines, readAll, FileMode, write, readBuffer, stderr, FileSeekPos, stdin, open, writeBytes, lines