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
Proc | Usage |
---|---|
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 & b | Concatenate 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
Proc | Usage |
---|---|
newSeq | Create a new sequence of a given length |
newSeqOfCap | Create a new sequence with zero length and a given capacity |
setLen | Set the length of a sequence |
len | Return the length of a sequence |
@ | Turn an array into a sequence |
add | Add an item to the sequence |
insert | Insert an item at a specific position |
delete | Delete an item while preserving the order of elements (O(n) operation) |
del | O(1) removal, doesn't preserve the order |
pop | Remove and return last item of a sequence |
x & y | Concatenate 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:
- sequtils module for operations on container types (including strings)
- json module for a structure which allows heterogeneous members
- lists module for linked lists
Sets
Built-in bit sets.
Proc | Usage |
---|---|
incl | Include element y in the set x |
excl | Exclude element y from the set x |
card | Return the cardinality of the set, i.e. the number of elements |
a * b | Intersection |
a + b | Union |
a - b | Difference |
contains | Check if an element is in the set |
a < b | Check if a is a subset of b |
See also:
- sets module for hash sets
- intsets module for efficient int sets
Numbers
Proc | Usage | Also known as (in other languages) |
---|---|---|
div | Integer division | // |
mod | Integer modulo (remainder) | % |
shl | Shift left | << |
shr | Shift right | >> |
ashr | Arithmetic shift right | |
and | Bitwise and | & |
or | Bitwise or | | |
xor | Bitwise xor | ^ |
not | Bitwise not (complement) | ~ |
toInt | Convert floating-point number into an int | |
toFloat | Convert an integer into a float |
See also:
- math module for mathematical operations like trigonometric functions, logarithms, square and cubic roots, etc.
- complex module for operations on complex numbers
- rationals module for rational numbers
Ordinals
Ordinal type includes integer, bool, character, and enumeration types, as well as their subtypes.
Proc | Usage |
---|---|
succ | Successor of the value |
pred | Predecessor of the value |
inc | Increment the ordinal |
dec | Decrement the ordinal |
high | Return the highest possible value |
low | Return the lowest possible value |
ord | Return int value of an ordinal value |
Misc
Proc | Usage |
---|---|
is | Check if two arguments are of the same type |
isnot | Negated version of is |
!= | Not equals |
addr | Take the address of a memory location |
T and F | Boolean and |
T or F | Boolean or |
T xor F | Boolean xor (exclusive or) |
not T | Boolean not |
a[^x] | Take the element at the reversed index x |
a .. b | Binary slice that constructs an interval [a, b] |
a ..^ b | Interval [a, b] but b as reversed index |
a ..< b | Interval [a, b) (excluded upper bound) |
runnableExamples | Create testable documentation |
Thread support for Nim.
Note: This is part of the system module. Do not import it directly. To activate thread support you need to compile with the --threads:on command line switch.
Nim's memory model for threads is quite different from other common programming languages (C, Pascal): Each thread has its own (garbage collected) heap and sharing of memory is restricted. This helps to prevent race conditions and improves efficiency. See the manual for details of this memory model.
Examples
import std/locks var thr: array[0..4, Thread[tuple[a,b: int]]] L: Lock proc threadFunc(interval: tuple[a,b: int]) {.thread.} = for i in interval.a..interval.b: acquire(L) # lock stdout echo i release(L) initLock(L) for i in 0..high(thr): thr[i] = createThread(threadFunc, (i*10, i*10+5)) joinThreads(thr) deinitLock(L)The run-time copy and reset implementation used by the deepCopy implementation and typeinfo module.
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.
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.
# Be sure to compile with --threads:on. # The channels and threads modules are part of system and should not be # imported. import std/os # Channels can either be: # - declared at the module level, or # - passed to procedures by ptr (raw pointer) -- see note on safety. # # For simplicity, in this example a channel is declared at module scope. # Channels are generic, and they include support for passing objects between # threads. # Note that objects passed through channels will be deeply copied. var chan: Channel[string] # This proc will be run in another thread using the threads module. proc firstWorker() = chan.send("Hello World!") # This is another proc to run in a background thread. This proc takes a while # to send the message since it sleeps for 2 seconds (or 2000 milliseconds). proc secondWorker() = sleep(2000) chan.send("Another message") # Initialize the channel. chan.open() # Launch the worker. var worker1: Thread[void] createThread(worker1, firstWorker) # Block until the message arrives, then print it out. echo chan.recv() # "Hello World!" # Wait for the thread to exit before moving on to the next example. worker1.joinThread() # Launch the other worker. var worker2: Thread[void] createThread(worker2, secondWorker) # This time, use a non-blocking approach with tryRecv. # Since the main thread is not blocked, it could be used to perform other # useful work while it waits for data to arrive on the channel. while true: let tried = chan.tryRecv() if tried.dataAvailable: echo tried.msg # "Another message" break echo "Pretend I'm doing useful work..." # For this example, sleep in order not to flood stdout with the above # message. sleep(400) # Wait for the second thread to exit before cleaning up the channel. worker2.joinThread() # Clean up the channel. 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:
Hello World! Pretend I'm doing useful work... Pretend I'm doing useful work... Pretend I'm doing useful work... Pretend I'm doing useful work... Pretend I'm doing useful work... 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:
proc worker(channel: ptr Channel[string]) = let greeting = channel[].recv() echo greeting proc localChannelExample() = # Use allocShared0 to allocate some shared-heap memory and zero it. # The usual warnings about dealing with raw pointers apply. Exercise caution. var channel = cast[ptr Channel[string]]( allocShared0(sizeof(Channel[string])) ) channel[].open() # Create a thread which will receive the channel as an argument. var thread: Thread[ptr Channel[string]] createThread(thread, worker, channel) channel[].send("Hello from the main thread!") # Clean up resources. thread.joinThread() channel[].close() deallocShared(channel) localChannelExample() # "Hello from the main thread!"
Types
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 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 AccessViolationDefect = object of Defect
- Raised for invalid memory access errors Source Edit
AccessViolationError {....deprecated: "See corresponding Defect".} = AccessViolationDefect
- Source Edit
AllocStats = object allocCount: int deallocCount: int
- Source Edit
any {....deprecated: "Deprecated since v1.5; Use auto instead.".} = distinct auto
- auto instead. See https://github.com/nim-lang/RFCs/issues/281 Source Edit Deprecated; Use
ArithmeticDefect = object of Defect
- Raised if any kind of arithmetic error occurred. Source Edit
ArithmeticError {....deprecated: "See corresponding Defect".} = ArithmeticDefect
- Source Edit
AssertionDefect = object of Defect
-
Raised when assertion is proved wrong.
Usually the result of using the assert() template.
Source Edit AssertionError {....deprecated: "See corresponding Defect".} = AssertionDefect
- Source Edit
AtomMemModel = distinct cint
- Source Edit
AtomType = SomeNumber | pointer | ptr | char | bool
- Type Class representing valid types for use with atomic procs Source Edit
BackwardsIndex = distinct int
- Type that is constructed by ^ for reversed array accesses. (See ^ template) Source Edit
BiggestFloat = float64
- is an alias for the biggest floating point type the Nim compiler supports. Currently this is float64, but it is platform-dependent in general. Source Edit
BiggestInt = int64
- is an alias for the biggest signed integer type the Nim compiler supports. Currently this is int64, but it is platform-dependent in general. Source Edit
BiggestUInt = uint64
- is an alias for the biggest unsigned integer type the Nim compiler supports. Currently this is uint32 for JS and uint64 for other targets. Source Edit
ByteAddress = int
- is the signed integer type that should be used for converting pointers to integer addresses for readability. Source Edit
CatchableError = object of Exception
- Abstract class for all exceptions that are catchable. Source Edit
cdouble {.importc: "double", nodecl.} = float64
- This is the same as the type double in C. Source Edit
clongdouble {.importc: "long double", nodecl.} = BiggestFloat
- This is the same as the type long double in C. This C type is not supported by Nim's code generator. Source Edit
clonglong {.importc: "long long", nodecl.} = int64
- This is the same as the type long long in C. Source Edit
cschar {.importc: "signed char", nodecl.} = int8
- This is the same as the type signed char in C. Source Edit
csize {.importc: "size_t", nodecl, ...deprecated: "use `csize_t` instead".} = int
- size_t in C. Don't use it. Source Edit This isn't the same as
cstringArray {.importc: "char**", nodecl.} = ptr UncheckedArray[cstring]
- This is binary compatible to the type char** in C. The array's high value is large enough to disable bounds checking in practice. Use cstringArrayToSeq proc to convert it into a seq[string]. Source Edit
cuchar {.importc: "unsigned char", nodecl, ...deprecated: "use `char` or `uint8` instead".} = char
- uint8 instead. Source Edit Deprecated: Use
cuint {.importc: "unsigned int", nodecl.} = uint32
- This is the same as the type unsigned int in C. Source Edit
culong {.importc: "unsigned long", nodecl.} = uint
- This is the same as the type unsigned long in C. Source Edit
culonglong {.importc: "unsigned long long", nodecl.} = uint64
- This is the same as the type unsigned long long in C. Source Edit
cushort {.importc: "unsigned short", nodecl.} = uint16
- This is the same as the type unsigned short in C. Source Edit
DeadThreadDefect = object of Defect
- Raised if it is attempted to send a message to a dead thread. Source Edit
DeadThreadError {....deprecated: "See corresponding Defect".} = DeadThreadDefect
- Source Edit
Defect = object of Exception
- Abstract base class for all exceptions that Nim's runtime raises but that are strictly uncatchable as they can also be mapped to a quit / trap / exit operation. Source Edit
DivByZeroDefect = object of ArithmeticDefect
- Raised for runtime integer divide-by-zero errors. Source Edit
DivByZeroError {....deprecated: "See corresponding Defect".} = DivByZeroDefect
- Source Edit
Endianness = enum littleEndian, bigEndian
- Type describing the endianness of a processor. Source Edit
Exception {.compilerproc, magic: "Exception".} = object of RootObj parent*: ref Exception ## Parent exception (can be used as a stack). name*: cstring ## The exception's name is its Nim identifier. ## This field is filled automatically in the ## `raise` statement. msg* {.exportc: "message".}: string ## The exception's message. Not ## providing an exception message ## is bad style. when defined(js): trace: string else: trace: seq[StackTraceEntry] up: ref Exception
-
Base exception class.
Each exception has to inherit from Exception. See the full exception hierarchy.
Source Edit ExecIOEffect = object of IOEffect
- Effect describing an executing IO operation. Source Edit
FieldDefect = object of Defect
- Raised if a record field is not accessible because its discriminant's value does not fit. Source Edit
FieldError {....deprecated: "See corresponding Defect".} = FieldDefect
- Source Edit
FileSeekPos = enum fspSet, ## Seek to absolute value fspCur, ## Seek relative to current position fspEnd ## Seek relative to end
- Position relative to which seek should happen. Source Edit
FloatDivByZeroDefect = object of FloatingPointDefect
-
Raised by division by zero.
Divisor is zero and dividend is a finite nonzero number.
Source Edit FloatDivByZeroError {....deprecated: "See corresponding Defect".} = FloatDivByZeroDefect
- Source Edit
FloatInexactDefect = object of FloatingPointDefect
-
Raised for inexact results.
The operation produced a result that cannot be represented with infinite precision -- for example: 2.0 / 3.0, log(1.1)
Note: Nim currently does not detect these!
Source Edit FloatInexactError {....deprecated: "See corresponding Defect".} = FloatInexactDefect
- Source Edit
FloatingPointDefect = object of Defect
- Base class for floating point exceptions. Source Edit
FloatingPointError {....deprecated: "See corresponding Defect".} = FloatingPointDefect
- Source Edit
FloatInvalidOpDefect = object of FloatingPointDefect
-
Raised by invalid operations according to IEEE.
Raised by 0.0/0.0, for example.
Source Edit FloatInvalidOpError {....deprecated: "See corresponding Defect".} = FloatInvalidOpDefect
- Source Edit
FloatOverflowDefect = object of FloatingPointDefect
-
Raised for overflows.
The operation produced a result that exceeds the range of the exponent.
Source Edit FloatOverflowError {....deprecated: "See corresponding Defect".} = FloatOverflowDefect
- Source Edit
FloatUnderflowDefect = object of FloatingPointDefect
-
Raised for underflows.
The operation produced a result that is too small to be represented as a normal number.
Source Edit FloatUnderflowError {....deprecated: "See corresponding Defect".} = FloatUnderflowDefect
- Source Edit
HSlice[T; U] = object a*: T ## The lower bound (inclusive). b*: U ## The upper bound (inclusive).
- "Heterogeneous" slice type. Source Edit
IndexDefect = object of Defect
- Raised if an array index is out of bounds. Source Edit
IndexError {....deprecated: "See corresponding Defect".} = IndexDefect
- Source Edit
int {.magic: "Int".}
- Default integer type; bitwidth depends on architecture, but is always the same as a pointer. Source Edit
IOEffect = object of RootEffect
- IO effect. Source Edit
IOError = object of CatchableError
- Raised if an IO error occurred. Source Edit
KeyError = object of ValueError
-
Raised if a key cannot be found in a table.
Mostly used by the tables module, it can also be raised by other collection modules like sets or strtabs.
Source Edit LibraryError = object of OSError
- Raised if a dynamic library could not be loaded. Source Edit
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
NilAccessDefect = object of Defect
- Raised on dereferences of nil pointers. Source Edit
NilAccessError {....deprecated: "See corresponding Defect".} = NilAccessDefect
- Source Edit
NimNode {.magic: "PNimrodNode".} = ref NimNodeObj
- Represents a Nim AST node. Macros operate on this type. Source Edit
ObjectAssignmentDefect = object of Defect
- Raised if an object gets assigned to its parent's object. Source Edit
ObjectAssignmentError {....deprecated: "See corresponding Defect".} = ObjectAssignmentDefect
- Source Edit
ObjectConversionDefect = object of Defect
- Raised if an object is converted to an incompatible object type. You can use of operator to check if conversion will succeed. Source Edit
ObjectConversionError {....deprecated: "See corresponding Defect".} = ObjectConversionDefect
- Source Edit
openArray[T] {.magic: "OpenArray".}
- Generic type to construct open arrays. Open arrays are implemented as a pointer to the array data and a length field. Source Edit
Ordinal[T] {.magic: Ordinal.}
- Generic ordinal type. Includes integer, bool, character, and enumeration types as well as their subtypes. See also SomeOrdinal. Source Edit
OSError = object of CatchableError errorCode*: int32 ## OS-defined error code describing this error.
- Raised if an operating system service failed. Source Edit
OutOfMemDefect = object of Defect
- Raised for unsuccessful attempts to allocate memory. Source Edit
OutOfMemError {....deprecated: "See corresponding Defect".} = OutOfMemDefect
- Source Edit
OverflowDefect = object of ArithmeticDefect
-
Raised for runtime integer overflows.
This happens for calculations whose results are too large to fit in the provided bits.
Source Edit OverflowError {....deprecated: "See corresponding Defect".} = OverflowDefect
- Source Edit
PFrame = ptr TFrame
- Represents a runtime frame of the call stack; part of the debugger API. Source Edit
pointer {.magic: Pointer.}
- Built-in pointer type, use the addr operator to get a pointer to a variable. Source Edit
Positive = range[1 .. high(int)]
- is an int type ranging from one to the maximum value of an int. This type is often useful for documentation and debugging. Source Edit
RangeDefect = object of Defect
- Raised if a range check error occurred. Source Edit
RangeError {....deprecated: "See corresponding Defect".} = RangeDefect
- Source Edit
ReadIOEffect = object of IOEffect
- Effect describing a read IO operation. Source Edit
ReraiseDefect = object of Defect
- Raised if there is no exception to reraise. Source Edit
ReraiseError {....deprecated: "See corresponding Defect".} = ReraiseDefect
- Source Edit
ResourceExhaustedError = object of CatchableError
- Raised if a resource request could not be fulfilled. Source Edit
RootEffect {.compilerproc.} = object of RootObj
-
Base effect class.
Each effect should inherit from RootEffect unless you know what you're doing.
Source Edit RootObj {.compilerproc, inheritable.} = object
-
The root of Nim's object hierarchy.
Objects should inherit from RootObj or one of its descendants. However, objects that have no ancestor are also allowed.
Source Edit SomeFloat = float | float32 | float64
- Type class matching all floating point number types. Source Edit
SomeInteger = SomeSignedInt | SomeUnsignedInt
- Type class matching all integer types. Source Edit
SomeNumber = SomeInteger | SomeFloat
- Type class matching all number types. Source Edit
SomeOrdinal = int | int8 | int16 | int32 | int64 | bool | enum | uint | uint8 | uint16 | uint32 | uint64
- Type class matching all ordinal types; however this includes enums with holes. See also Ordinal Source Edit
SomeSignedInt = int | int8 | int16 | int32 | int64
- Type class matching all signed integer types. Source Edit
SomeUnsignedInt = uint | uint8 | uint16 | uint32 | uint64
- Type class matching all unsigned integer types. Source Edit
StackOverflowDefect = object of Defect
- Raised if the hardware stack used for subroutine calls overflowed. Source Edit
StackOverflowError {....deprecated: "See corresponding Defect".} = StackOverflowDefect
- Source Edit
StackTraceEntry = object procname*: cstring ## Name of the proc that is currently executing. line*: int ## Line number of the proc that is currently executing. filename*: cstring ## Filename of the proc that is currently executing. when NimStackTraceMsgs: frameMsg*: string ## When a stacktrace is generated in a given frame and ## rendered at a later time, we should ensure the stacktrace ## data isn't invalidated; any pointer into PFrame is ## subject to being invalidated so shouldn't be stored. when defined(nimStackTraceOverride): programCounter*: uint ## Program counter - will be used to get the rest of the info, ## when `$` is called on this type. We can't use ## "cuintptr_t" in here. procnameStr*, filenameStr*: string ## GC-ed alternatives to "procname" and "filename"
- In debug mode exceptions store the stack trace that led to them. A StackTraceEntry is a single entry of the stack trace. Source Edit
TaintedString {....deprecated: "Deprecated since 1.5".} = string
- Source Edit
TFrame {.importc, nodecl, final.} = object prev*: PFrame ## Previous frame; used for chaining the call stack. procname*: cstring ## Name of the proc that is currently executing. line*: int ## Line number of the proc that is currently executing. filename*: cstring ## Filename of the proc that is currently executing. len*: int16 ## Length of the inspectable slots. calldepth*: int16 ## Used for max call depth checking. when NimStackTraceMsgs: frameMsgLen*: int ## end position in frameMsgBuf for this frame.
- The frame itself. Source Edit
TimeEffect = object of RootEffect
- Time effect. Source Edit
typed {.magic: Stmt.}
- Meta type to denote an expression that is resolved (for templates). Source Edit
TypeOfMode = enum typeOfProc, ## Prefer the interpretation that means `x` is a proc call. typeOfIter ## Prefer the interpretation that means `x` is an iterator call.
- Possible modes of typeof. Source Edit
UncheckedArray[T] {.magic: "UncheckedArray".}
- Source Edit
untyped {.magic: Expr.}
- Meta type to denote an expression that is not resolved (for templates). Source Edit
ValueError = object of CatchableError
- Raised for string and object conversion errors. Source Edit
WriteIOEffect = object of IOEffect
- Effect describing a write IO operation. Source Edit
Vars
ATOMIC_ACQ_REL: AtomMemModel
- Full barrier in both directions and synchronizes with acquire loads and release stores in another thread. Source Edit
ATOMIC_ACQUIRE: AtomMemModel
- Barrier to hoisting of code and synchronizes with release (or stronger) semantic stores from another thread. Source Edit
ATOMIC_CONSUME: AtomMemModel
- Data dependency only for both barrier and synchronization with another thread. Source Edit
ATOMIC_RELAXED: AtomMemModel
- No barriers or synchronization. Source Edit
ATOMIC_RELEASE: AtomMemModel
- Barrier to sinking of code and synchronizes with acquire (or stronger) semantic loads from another thread. Source Edit
ATOMIC_SEQ_CST: AtomMemModel
- Full barrier in both directions and synchronizes with acquire loads and release stores in all threads. Source Edit
errorMessageWriter: (proc (msg: string) {....tags: [WriteIOEffect], gcsafe, locks: 0, nimcall.})
- Function that will be called instead of stdmsg.write when printing stacktrace. Unstable API. Source Edit
globalRaiseHook: proc (e: ref Exception): bool {.nimcall, ...gcsafe, locks: 0.}
-
With this hook you can influence exception handling on a global level. If not nil, every 'raise' statement ends up calling this hook.Warning: Ordinary application code should never set this hook! You better know what you do when setting this.
If globalRaiseHook returns false, the exception is caught and does not propagate further through the call stack.
Source Edit localRaiseHook: proc (e: ref Exception): bool {.nimcall, ...gcsafe, locks: 0.}
-
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 onUnhandledException: (proc (errorMsg: string) {.nimcall, ...gcsafe.})
-
Set this error handler to override the existing behaviour on an unhandled exception.
The default is to write a stacktrace to stderr and then call quit(1). Unstable API.
Source Edit outOfMemHook: proc () {.nimcall, ...tags: [], gcsafe, locks: 0, ...raises: [].}
-
Set this variable to provide a procedure that should be called in case of an out of memory event. The standard handler writes an error message and terminates the program.
outOfMemHook can be used to raise an exception in case of OOM like so:
var gOutOfMem: ref EOutOfMemory new(gOutOfMem) # need to be allocated *before* OOM really happened! gOutOfMem.msg = "out of memory" proc handleOOM() = raise gOutOfMem system.outOfMemHook = handleOOM
If the handler does not raise an exception, ordinary control flow continues and the program is terminated.
Source Edit programResult: int
- deprecated, prefer quit or exitprocs.getProgramResult, exitprocs.setProgramResult. Source Edit
unhandledExceptionHook: proc (e: ref Exception) {.nimcall, ...tags: [], gcsafe, locks: 0, ...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
Consts
appType: string = ""
- A string that describes the application type. Possible values: "console", "gui", "lib". Source Edit
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
CompilerVersionMajor: int = 1
-
major version number for the current compiler. TODO: change to 0 in next csources
when CompilerVersionMajor > 0: echo "stability cargo culting"
Source Edit CompilerVersionMinor: int = 6
- minor version number for the current compiler. TODO: change to 1 in next csources Source Edit
CompilerVersionPatch: int = 0
- patch version number for the current compiler. TODO: change to 0 in next csources Source Edit
CompileTime: string = "00:00:00"
- The time (in UTC) of compilation as a string of the form HH:MM:SS. This works thanks to compiler magic. Source Edit
cpuEndian: Endianness = littleEndian
- The endianness of the target CPU. This is a valuable piece of information for low-level code only. This works thanks to compiler magic. Source Edit
hostCPU: string = ""
-
A string that describes the host CPU.
Possible values: "i386", "alpha", "powerpc", "powerpc64", "powerpc64el", "sparc", "amd64", "mips", "mipsel", "arm", "arm64", "mips64", "mips64el", "riscv32", "riscv64", '"loongarch64"'.
Source Edit hostOS: string = ""
-
A string that describes the host operating system.
Possible values: "windows", "macosx", "linux", "netbsd", "freebsd", "openbsd", "solaris", "aix", "haiku", "standalone".
Source Edit Inf = 0x7FF0000000000000'f64
- Contains the IEEE floating point value of positive infinity. Source Edit
isMainModule: bool = false
- True only when accessed in the main module. This works thanks to compiler magic. It is useful to embed testing code in a module. Source Edit
NaN = 0x7FF7FFFFFFFFFFFF'f64
-
Contains an IEEE floating point value of Not A Number.
Note that you cannot compare a floating point value to this value and expect a reasonable result - use the isNaN or classify procedure in the math module for checking for NaN.
Source Edit NegInf = 0xFFF0000000000000'f64
- Contains the IEEE floating point value of negative infinity. Source Edit
NimMajor: int = 1
-
is the major number of Nim's version. Example: TODO: remove in next csources .. code-block:: Nim
Source Editwhen (NimMajor, NimMinor, NimPatch) >= (1, 3, 1): discard
NimVersion: string = "1.6.0"
- the compiler version as a string. Source Edit
QuitFailure = 1
- is the value that should be passed to quit to indicate failure. Source Edit
QuitSuccess = 0
- is the value that should be passed to quit to indicate success. Source Edit
StdlibMajor: int = 1
-
standard library major version TODO: change to 0 in next csources
Example:
when (StdlibMajor, StdlibMinor, StdlibPatch) >= (1, 3, 1): discard
Source Edit StdlibMinor: int = 6
- standard library minor version TODO: change to 1 in next csources Source Edit
StdlibPatch: int = 0
- standard library patch version TODO: change to 0 in next csources Source Edit
StdlibVersion: string = "1.6.0"
- the standard library version Source Edit
Procs
proc `$`[Enum: enum](x: Enum): string {.magic: "EnumToStr", noSideEffect, ...raises: [], tags: [].}
-
The stringify operator for an enumeration argument. This works for any enumeration type thanks to compiler magic.
If a $ operator for a concrete enumeration is provided, this is used instead. (In other words: Overwriting is possible.)
Source Edit proc `%%`(x, y: int): int {.inline, ...raises: [], tags: [].}
-
Treats x and y as unsigned and compute the modulo of x and y.
The result is truncated to fit into the result. This implements modulo arithmetic. No overflow errors are possible.
Source Edit proc `&=`(x: var string; y: string) {.magic: "AppendStrStr", noSideEffect, ...raises: [], tags: [].}
-
Appends in place to a string.
var a = "abc" a &= "de" # a <- "abcde"
Source Edit proc `&`(x, y: char): string {.magic: "ConStrStr", noSideEffect, ...raises: [], tags: [].}
-
Concatenates characters x and y into a string.
assert('a' & 'b' == "ab")
Source Edit proc `&`(x, y: string): string {.magic: "ConStrStr", noSideEffect, ...raises: [], tags: [].}
-
Concatenates strings x and y.
assert("ab" & "cd" == "abcd")
Source Edit proc `&`(x: char; y: string): string {.magic: "ConStrStr", noSideEffect, ...raises: [], tags: [].}
-
Concatenates x with y.
assert('a' & "bc" == "abc")
Source Edit proc `&`(x: string; y: char): string {.magic: "ConStrStr", noSideEffect, ...raises: [], tags: [].}
-
Concatenates x with y.
assert("ab" & 'c' == "abc")
Source Edit proc `&`[T](x, y: sink seq[T]): seq[T] {.noSideEffect.}
-
Concatenates two sequences.
Requires copying of the sequences.
See also:
assert(@[1, 2, 3, 4] & @[5, 6] == @[1, 2, 3, 4, 5, 6])
Source Edit proc `&`[T](x: sink seq[T]; y: sink T): seq[T] {.noSideEffect.}
-
Appends element y to the end of the sequence.
Requires copying of the sequence.
See also:
assert(@[1, 2, 3] & 4 == @[1, 2, 3, 4])
Source Edit proc `&`[T](x: sink T; y: sink seq[T]): seq[T] {.noSideEffect.}
-
Prepends the element x to the beginning of the sequence.
Requires copying of the sequence.
assert(1 & @[2, 3, 4] == @[1, 2, 3, 4])
Source Edit proc `*%`(x, y: int): int {.inline, ...raises: [], tags: [].}
-
Treats x and y as unsigned and multiplies them.
The result is truncated to fit into the result. This implements modulo arithmetic. No overflow errors are possible.
Source Edit proc `*=`[T: float | float32 | float64](x: var T; y: T) {.inline, noSideEffect.}
- Multiplies in place a floating point number. Source Edit
proc `*=`[T: SomeInteger](x: var T; y: T) {.inline, noSideEffect.}
- Binary *= operator for integers. Source Edit
proc `*`(x, y: float32): float32 {.magic: "MulF64", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `*`(x, y: int): int {.magic: "MulI", noSideEffect, ...raises: [], tags: [].}
- Binary * operator for an integer. Source Edit
proc `*`(x, y: uint): uint {.magic: "MulU", noSideEffect, ...raises: [], tags: [].}
- Binary * operator for unsigned integers. Source Edit
func `*`[T](x, y: set[T]): set[T] {.magic: "MulSet", ...raises: [], tags: [].}
-
This operator computes the intersection of two sets.
Example:
assert {1, 2, 3} * {2, 3, 4} == {2, 3}
Source Edit proc `+%`(x, y: int): int {.inline, ...raises: [], tags: [].}
-
Treats x and y as unsigned and adds them.
The result is truncated to fit into the result. This implements modulo arithmetic. No overflow errors are possible.
Source Edit proc `+=`[T: float | float32 | float64](x: var T; y: T) {.inline, noSideEffect.}
- Increments in place a floating point number. Source Edit
proc `+=`[T: SomeInteger](x: var T; y: T) {.magic: "Inc", noSideEffect, ...raises: [], tags: [].}
- Increments an integer. Source Edit
proc `+`(x, y: float32): float32 {.magic: "AddF64", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `+`(x, y: int): int {.magic: "AddI", noSideEffect, ...raises: [], tags: [].}
- Binary + operator for an integer. Source Edit
proc `+`(x, y: uint): uint {.magic: "AddU", noSideEffect, ...raises: [], tags: [].}
- Binary + operator for unsigned integers. Source Edit
proc `+`(x: float): float {.magic: "UnaryPlusF64", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `+`(x: float32): float32 {.magic: "UnaryPlusF64", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `+`(x: int): int {.magic: "UnaryPlusI", noSideEffect, ...raises: [], tags: [].}
- Unary + operator for an integer. Has no effect. Source Edit
proc `+`(x: int16): int16 {.magic: "UnaryPlusI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `+`(x: int32): int32 {.magic: "UnaryPlusI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `+`(x: int64): int64 {.magic: "UnaryPlusI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
func `+`[T](x, y: set[T]): set[T] {.magic: "PlusSet", ...raises: [], tags: [].}
-
This operator computes the union of two sets.
Example:
assert {1, 2, 3} + {2, 3, 4} == {1, 2, 3, 4}
Source Edit func `+`[T](x: set[T]; y: T): set[T] {.inline.}
-
This operator computes the union of two sets, where the second set operand is derived by promoting a single element to a set containing that element.
Example:
assert {1, 2, 3} + 4 == {1, 2, 3, 4}
Source Edit proc `-%`(x, y: int): int {.inline, ...raises: [], tags: [].}
-
Treats x and y as unsigned and subtracts them.
The result is truncated to fit into the result. This implements modulo arithmetic. No overflow errors are possible.
Source Edit proc `-=`[T: float | float32 | float64](x: var T; y: T) {.inline, noSideEffect.}
- Decrements in place a floating point number. Source Edit
proc `-=`[T: SomeInteger](x: var T; y: T) {.magic: "Dec", noSideEffect, ...raises: [], tags: [].}
- Decrements an integer. Source Edit
proc `-`(a, b: AllocStats): AllocStats {....raises: [], tags: [].}
- Source Edit
proc `-`(x, y: float32): float32 {.magic: "SubF64", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `-`(x, y: int): int {.magic: "SubI", noSideEffect, ...raises: [], tags: [].}
- Binary - operator for an integer. Source Edit
proc `-`(x, y: uint): uint {.magic: "SubU", noSideEffect, ...raises: [], tags: [].}
- Binary - operator for unsigned integers. Source Edit
proc `-`(x: float): float {.magic: "UnaryMinusF64", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `-`(x: float32): float32 {.magic: "UnaryMinusF64", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `-`(x: int): int {.magic: "UnaryMinusI", noSideEffect, ...raises: [], tags: [].}
- Unary - operator for an integer. Negates x. Source Edit
proc `-`(x: int16): int16 {.magic: "UnaryMinusI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `-`(x: int32): int32 {.magic: "UnaryMinusI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `-`(x: int64): int64 {.magic: "UnaryMinusI64", noSideEffect, ...raises: [], tags: [].}
- Source Edit
func `-`[T](x, y: set[T]): set[T] {.magic: "MinusSet", ...raises: [], tags: [].}
-
This operator computes the difference of two sets.
Example:
assert {1, 2, 3} - {2, 3, 4} == {1}
Source Edit func `-`[T](x: set[T]; y: T): set[T] {.inline.}
-
This operator computes the difference of two sets, where the second set operand is derived by promoting a single element to a set containing that element.
Example:
assert {1, 2} - 2 == {1}
Source Edit proc `..`[T, U](a: sink T; b: sink U): HSlice[T, U] {.noSideEffect, inline, magic: "DotDot", ...raises: [], tags: [].}
-
Binary slice operator that constructs an interval [a, b], both a and b are inclusive.
Slices can also be used in the set constructor and in ordinal case statements, but then they are special-cased by the compiler.
let a = [10, 20, 30, 40, 50] echo a[2 .. 3] # @[30, 40]
Source Edit proc `..`[T](b: sink T): HSlice[int, T] {.noSideEffect, inline, magic: "DotDot", ...deprecated: "replace `..b` with `0..b`", raises: [], tags: [].}
-
slice operator that constructs an interval [default(int), b].
let a = [10, 20, 30, 40, 50] echo a[.. 2] # @[10, 20, 30]
Source Edit
Unary proc `/%`(x, y: int): int {.inline, ...raises: [], tags: [].}
-
Treats x and y as unsigned and divides them.
The result is truncated to fit into the result. This implements modulo arithmetic. No overflow errors are possible.
Source Edit proc `/=`(x: var float64; y: float64) {.inline, noSideEffect, ...raises: [], tags: [].}
- Divides in place a floating point number. Source Edit
proc `/=`[T: float | float32](x: var T; y: T) {.inline, noSideEffect.}
- Divides in place a floating point number. Source Edit
proc `/`(x, y: float32): float32 {.magic: "DivF64", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `/`(x, y: int): float {.inline, noSideEffect, ...raises: [], tags: [].}
-
Division of integers that results in a float.
See also:
echo 7 / 5 # => 1.4
Source Edit proc `<%`(x, y: int): bool {.inline, ...raises: [], tags: [].}
- Treats x and y as unsigned and compares them. Returns true if unsigned(x) < unsigned(y). Source Edit
proc `<=%`(x, y: int): bool {.inline, ...raises: [], tags: [].}
- Treats x and y as unsigned and compares them. Returns true if unsigned(x) <= unsigned(y). Source Edit
proc `<=`(x, y: char): bool {.magic: "LeCh", noSideEffect, ...raises: [], tags: [].}
-
Compares two chars and returns true if x is lexicographically before y (uppercase letters come before lowercase letters).
Example:
let a = 'a' b = 'b' c = 'Z' assert a <= b assert a <= a assert not (a <= c)
Source Edit proc `<=`(x, y: cstring): bool {.magic: "LePtr", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `<=`(x, y: float32): bool {.magic: "LeF64", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `<=`(x, y: int): bool {.magic: "LeI", noSideEffect, ...raises: [], tags: [].}
- Returns true if x is less than or equal to y. Source Edit
proc `<=`(x, y: pointer): bool {.magic: "LePtr", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `<=`(x, y: string): bool {.magic: "LeStr", noSideEffect, ...raises: [], tags: [].}
-
Compares two strings and returns true if x is lexicographically before y (uppercase letters come before lowercase letters).
Example:
let a = "abc" b = "abd" c = "ZZZ" assert a <= b assert a <= a assert not (a <= c)
Source Edit proc `<=`(x, y: uint): bool {.magic: "LeU", noSideEffect, ...raises: [], tags: [].}
- Returns true if x <= y. Source Edit
proc `<=`[Enum: enum](x, y: Enum): bool {.magic: "LeEnum", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `<=`[T: tuple](x, y: T): bool
- Generic lexicographic <= operator for tuples that is lifted from the components of x and y. This implementation uses cmp. Source Edit
proc `<=`[T](x, y: ref T): bool {.magic: "LePtr", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `<=`[T](x, y: set[T]): bool {.magic: "LeSet", noSideEffect, ...raises: [], tags: [].}
-
Returns true if x is a subset of y.
A subset x has all of its members in y and y doesn't necessarily have more members than x. That is, x can be equal to y.
Example:
let a = {3, 5} b = {1, 3, 5, 7} c = {2} assert a <= b assert a <= a assert not (a <= c)
Source Edit proc `<`(x, y: char): bool {.magic: "LtCh", noSideEffect, ...raises: [], tags: [].}
-
Compares two chars and returns true if x is lexicographically before y (uppercase letters come before lowercase letters).
Example:
let a = 'a' b = 'b' c = 'Z' assert a < b assert not (a < a) assert not (a < c)
Source Edit proc `<`(x, y: int): bool {.magic: "LtI", noSideEffect, ...raises: [], tags: [].}
- Returns true if x is less than y. Source Edit
proc `<`(x, y: string): bool {.magic: "LtStr", noSideEffect, ...raises: [], tags: [].}
-
Compares two strings and returns true if x is lexicographically before y (uppercase letters come before lowercase letters).
Example:
let a = "abc" b = "abd" c = "ZZZ" assert a < b assert not (a < a) assert not (a < c)
Source Edit proc `<`(x, y: uint): bool {.magic: "LtU", noSideEffect, ...raises: [], tags: [].}
- Returns true if x < y. Source Edit
proc `<`[Enum: enum](x, y: Enum): bool {.magic: "LtEnum", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `<`[T: tuple](x, y: T): bool
- Generic lexicographic < operator for tuples that is lifted from the components of x and y. This implementation uses cmp. Source Edit
proc `<`[T](x, y: ptr T): bool {.magic: "LtPtr", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `<`[T](x, y: ref T): bool {.magic: "LtPtr", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `<`[T](x, y: set[T]): bool {.magic: "LtSet", noSideEffect, ...raises: [], tags: [].}
-
Returns true if x is a strict or proper subset of y.
A strict or proper subset x has all of its members in y but y has more elements than y.
Example:
let a = {3, 5} b = {1, 3, 5, 7} c = {2} assert a < b assert not (a < a) assert not (a < c)
Source Edit proc `==`(x, y: bool): bool {.magic: "EqB", noSideEffect, ...raises: [], tags: [].}
- Checks for equality between two bool variables. Source Edit
proc `==`(x, y: char): bool {.magic: "EqCh", noSideEffect, ...raises: [], tags: [].}
- Checks for equality between two char variables. Source Edit
proc `==`(x, y: cstring): bool {.magic: "EqCString", noSideEffect, inline, ...raises: [], tags: [].}
- Checks for equality between two cstring variables. Source Edit
proc `==`(x, y: float32): bool {.magic: "EqF64", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `==`(x, y: int): bool {.magic: "EqI", noSideEffect, ...raises: [], tags: [].}
- Compares two integers for equality. Source Edit
proc `==`(x, y: pointer): bool {.magic: "EqRef", noSideEffect, ...raises: [], tags: [].}
-
Checks for equality between two pointer variables.
Example:
var # this is a wildly dangerous example a = cast[pointer](0) b = cast[pointer](nil) assert a == b # true due to the special meaning of `nil`/0 as a pointer
Source Edit proc `==`(x, y: string): bool {.magic: "EqStr", noSideEffect, ...raises: [], tags: [].}
- Checks for equality between two string variables. Source Edit
proc `==`(x, y: uint): bool {.magic: "EqI", noSideEffect, ...raises: [], tags: [].}
- Compares two unsigned integers for equality. Source Edit
proc `==`(x: string; y: typeof(nil) | typeof(nil)): bool {. error: "\'nil\' is now invalid for \'string\'".}
- Source Edit
proc `==`(x: typeof(nil) | typeof(nil); y: string): bool {. error: "\'nil\' is now invalid for \'string\'".}
- Source Edit
proc `==`[Enum: enum](x, y: Enum): bool {.magic: "EqEnum", noSideEffect, ...raises: [], tags: [].}
-
Checks whether values within the same enum have the same underlying value.
Example:
type Enum1 = enum field1 = 3, field2 Enum2 = enum place1, place2 = 3 var e1 = field1 e2 = place2.ord.Enum1 assert e1 == e2 assert not compiles(e1 == place2) # raises error
Source Edit proc `==`[T: proc](x, y: T): bool {.magic: "EqProc", noSideEffect, ...raises: [], tags: [].}
- Checks that two proc variables refer to the same procedure. Source Edit
proc `==`[T: tuple | object](x, y: T): bool
- Generic == operator for tuples that is lifted from the components. of x and y. Source Edit
proc `==`[T](x, y: ptr T): bool {.magic: "EqRef", noSideEffect, ...raises: [], tags: [].}
- Checks that two ptr variables refer to the same item. Source Edit
proc `==`[T](x, y: ref T): bool {.magic: "EqRef", noSideEffect, ...raises: [], tags: [].}
- Checks that two ref variables refer to the same item. Source Edit
proc `==`[T](x, y: seq[T]): bool {.noSideEffect.}
- Generic equals operator for sequences: relies on a equals operator for the element type T. Source Edit
proc `==`[T](x, y: set[T]): bool {.magic: "EqSet", noSideEffect, ...raises: [], tags: [].}
-
Checks for equality between two variables of type set.
Example:
assert {1, 2, 2, 3} == {1, 2, 3} # duplication in sets is ignored
Source Edit proc `=`[T](dest: var T; src: T) {.noSideEffect, magic: "Asgn", ...raises: [], tags: [].}
- Source Edit
proc `=copy`[T](dest: var T; src: T) {.noSideEffect, magic: "Asgn", ...raises: [], tags: [].}
- Source Edit
proc `=destroy`[T](x: var T) {.inline, magic: "Destroy", ...raises: [], tags: [].}
- Generic destructor implementation that can be overridden. Source Edit
proc `=sink`[T](x: var T; y: T) {.inline, magic: "Asgn", ...raises: [], tags: [].}
- Generic sink implementation that can be overridden. Source Edit
proc `=trace`[T](x: var T; env: pointer) {.inline, magic: "Trace", ...raises: [], tags: [].}
- Generic trace implementation that can be overridden. Source Edit
proc `@`[IDX, T](a: sink array[IDX, T]): seq[T] {.magic: "ArrToSeq", noSideEffect, ...raises: [], tags: [].}
-
Turns an array into a sequence.
This most often useful for constructing sequences with the array constructor: @[1, 2, 3] has the type seq[int], while [1, 2, 3] has the type array[0..2, int].
let a = [1, 3, 5] b = "foo" echo @a # => @[1, 3, 5] echo @b # => @['f', 'o', 'o']
Source Edit proc `@`[T](a: openArray[T]): seq[T]
-
Turns an openArray into a sequence.
This is not as efficient as turning a fixed length array into a sequence as it always copies every element of a.
Source Edit proc `[]=`(s: var string; i: BackwardsIndex; x: char) {.inline, ...raises: [], tags: [].}
- Source Edit
proc `[]=`[I: Ordinal; T, S](a: T; i: I; x: sink S) {.noSideEffect, magic: "ArrPut", ...raises: [], tags: [].}
- Source Edit
proc `[]=`[Idx, T; U, V: Ordinal](a: var array[Idx, T]; x: HSlice[U, V]; b: openArray[T])
-
Slice assignment for arrays.
var a = [10, 20, 30, 40, 50] a[1..2] = @[99, 88] assert a == [10, 99, 88, 40, 50]
Source Edit proc `[]=`[Idx, T](a: var array[Idx, T]; i: BackwardsIndex; x: T) {.inline.}
- Source Edit
proc `[]=`[T, U: Ordinal](s: var string; x: HSlice[T, U]; b: string)
-
Slice assignment for strings.
If b.len is not exactly the number of elements that are referred to by x, a splice is performed:
Example:
var s = "abcdefgh" s[1 .. ^2] = "xyz" assert s == "axyzh"
Source Edit proc `[]=`[T; U, V: Ordinal](s: var seq[T]; x: HSlice[U, V]; b: openArray[T])
-
Slice assignment for sequences.
If b.len is not exactly the number of elements that are referred to by x, a splice is performed.
Example:
var s = @"abcdefgh" s[1 .. ^2] = @"xyz" assert s == @"axyzh"
Source Edit proc `[]=`[T](s: var openArray[T]; i: BackwardsIndex; x: T) {.inline.}
- Source Edit
proc `[]`(s: var string; i: BackwardsIndex): var char {.inline, ...raises: [], tags: [].}
- Source Edit
proc `[]`[I: Ordinal; T](a: T; i: I): T {.noSideEffect, magic: "ArrGet", ...raises: [], tags: [].}
- Source Edit
proc `[]`[Idx, T; U, V: Ordinal](a: array[Idx, T]; x: HSlice[U, V]): seq[T]
-
Slice operation for arrays. Returns the inclusive range [a[x.a], a[x.b]]:
var a = [1, 2, 3, 4] assert a[0..2] == @[1, 2, 3]
Source Edit proc `[]`[Idx, T](a: array[Idx, T]; i: BackwardsIndex): T {.inline.}
- Source Edit
proc `[]`[Idx, T](a: var array[Idx, T]; i: BackwardsIndex): var T {.inline.}
- Source Edit
proc `[]`[T, U: Ordinal](s: string; x: HSlice[T, U]): string {.inline.}
-
Slice operation for strings. Returns the inclusive range [s[x.a], s[x.b]]:
var s = "abcdef" assert s[1..3] == "bcd"
Source Edit proc `[]`[T; U, V: Ordinal](s: openArray[T]; x: HSlice[U, V]): seq[T]
-
Slice operation for sequences. Returns the inclusive range [s[x.a], s[x.b]]:
var s = @[1, 2, 3, 4] assert s[0..2] == @[1, 2, 3]
Source Edit proc `[]`[T](s: openArray[T]; i: BackwardsIndex): T {.inline.}
- Source Edit
proc `[]`[T](s: var openArray[T]; i: BackwardsIndex): var T {.inline.}
- Source Edit
proc `addr`[T](x: T): ptr T {.magic: "Addr", noSideEffect, ...raises: [], tags: [].}
-
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.
See also:
var buf: seq[char] = @['a','b','c'] p = buf[1].addr echo p.repr # ref 0x7faa35c40059 --> 'b' echo p[] # b
Source Edit proc `and`(a, b: typedesc): typedesc {.magic: "TypeTrait", noSideEffect, ...raises: [], tags: [].}
- Constructs an and meta class. Source Edit
proc `and`(x, y: bool): bool {.magic: "And", noSideEffect, ...raises: [], tags: [].}
-
Boolean and; returns true if x == y == true (if both arguments are true).
Evaluation is lazy: if x is false, y will not even be evaluated.
Source Edit proc `and`(x, y: int): int {.magic: "BitandI", noSideEffect, ...raises: [], tags: [].}
-
Computes the bitwise and of numbers x and y.
Example:
assert (0b0011 and 0b0101) == 0b0001 assert (0b0111 and 0b1100) == 0b0100
Source Edit proc `and`(x, y: int8): int8 {.magic: "BitandI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `and`(x, y: int16): int16 {.magic: "BitandI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `and`(x, y: int32): int32 {.magic: "BitandI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `and`(x, y: int64): int64 {.magic: "BitandI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `and`(x, y: uint): uint {.magic: "BitandI", noSideEffect, ...raises: [], tags: [].}
- Computes the bitwise and of numbers x and y. Source Edit
proc `and`(x, y: uint8): uint8 {.magic: "BitandI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `and`(x, y: uint16): uint16 {.magic: "BitandI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `and`(x, y: uint32): uint32 {.magic: "BitandI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `and`(x, y: uint64): uint64 {.magic: "BitandI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `div`(x, y: int): int {.magic: "DivI", noSideEffect, ...raises: [], tags: [].}
-
Computes the integer division.
This is roughly the same as math.trunc(x/y).int.
Example:
assert (1 div 2) == 0 assert (2 div 2) == 1 assert (3 div 2) == 1 assert (7 div 3) == 2 assert (-7 div 3) == -2 assert (7 div -3) == -2 assert (-7 div -3) == 2
Source Edit proc `div`(x, y: uint): uint {.magic: "DivU", noSideEffect, ...raises: [], tags: [].}
- Computes the integer division for unsigned integers. This is roughly the same as trunc(x/y). Source Edit
proc `div`(x, y: uint16): uint16 {.magic: "DivU", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `div`(x, y: uint32): uint32 {.magic: "DivU", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `div`(x, y: uint64): uint64 {.magic: "DivU", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `is`[T, S](x: T; y: S): bool {.magic: "Is", noSideEffect, ...raises: [], tags: [].}
-
Checks if T is of the same type as S.
For a negated version, use isnot.
assert 42 is int assert @[1, 2] is seq proc test[T](a: T): int = when (T is int): return a else: return 0 assert(test[int](3) == 3) assert(test[string]("xyz") == 0)
Source Edit proc `mod`(x, y: int): int {.magic: "ModI", noSideEffect, ...raises: [], tags: [].}
-
Computes the integer modulo operation (remainder).
This is the same as x - (x div y) * y.
Example:
assert (7 mod 5) == 2 assert (-7 mod 5) == -2 assert (7 mod -5) == 2 assert (-7 mod -5) == -2
Source Edit proc `mod`(x, y: uint): uint {.magic: "ModU", noSideEffect, ...raises: [], tags: [].}
- Computes the integer modulo operation (remainder) for unsigned integers. This is the same as x - (x div y) * y. Source Edit
proc `mod`(x, y: uint16): uint16 {.magic: "ModU", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `mod`(x, y: uint32): uint32 {.magic: "ModU", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `mod`(x, y: uint64): uint64 {.magic: "ModU", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `not`(a: typedesc): typedesc {.magic: "TypeTrait", noSideEffect, ...raises: [], tags: [].}
- Constructs an not meta class. Source Edit
proc `not`(x: bool): bool {.magic: "Not", noSideEffect, ...raises: [], tags: [].}
- Boolean not; returns true if x == false. Source Edit
proc `not`(x: int): int {.magic: "BitnotI", noSideEffect, ...raises: [], tags: [].}
-
Computes the bitwise complement of the integer x.
Example:
assert not 0'u8 == 255 assert not 0'i8 == -1 assert not 1000'u16 == 64535 assert not 1000'i16 == -1001
Source Edit proc `not`(x: uint): uint {.magic: "BitnotI", noSideEffect, ...raises: [], tags: [].}
- Computes the bitwise complement of the integer x. Source Edit
proc `not`(x: uint16): uint16 {.magic: "BitnotI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `not`(x: uint32): uint32 {.magic: "BitnotI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `not`(x: uint64): uint64 {.magic: "BitnotI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `not`[T: ref or ptr](a: typedesc[T]; b: typeof(nil)): typedesc {. magic: "TypeTrait", noSideEffect, ...raises: [], tags: [].}
- Constructs a not nil type. Source Edit
proc `of`[T, S](x: T; y: typedesc[S]): bool {.magic: "Of", noSideEffect, ...raises: [], tags: [].}
-
Checks if x is an instance of y.
Example:
type Base = ref object of RootObj Sub1 = ref object of Base Sub2 = ref object of Base Unrelated = ref object var base: Base = Sub1() # downcast doAssert base of Base # generates `CondTrue` (statically true) doAssert base of Sub1 doAssert base isnot Sub1 doAssert not (base of Sub2) base = Sub2() # re-assign doAssert base of Sub2 doAssert Sub2(base) != nil # upcast doAssertRaises(ObjectConversionDefect): discard Sub1(base) var sub1 = Sub1() doAssert sub1 of Base doAssert sub1.Base of Sub1 doAssert not compiles(base of Unrelated)
Source Edit proc `or`(a, b: typedesc): typedesc {.magic: "TypeTrait", noSideEffect, ...raises: [], tags: [].}
- Constructs an or meta class. Source Edit
proc `or`(x, y: bool): bool {.magic: "Or", noSideEffect, ...raises: [], tags: [].}
-
Boolean or; returns true if not (not x and not y) (if any of the arguments is true).
Evaluation is lazy: if x is true, y will not even be evaluated.
Source Edit proc `or`(x, y: int): int {.magic: "BitorI", noSideEffect, ...raises: [], tags: [].}
-
Computes the bitwise or of numbers x and y.
Example:
assert (0b0011 or 0b0101) == 0b0111 assert (0b0111 or 0b1100) == 0b1111
Source Edit proc `or`(x, y: int16): int16 {.magic: "BitorI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `or`(x, y: int32): int32 {.magic: "BitorI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `or`(x, y: int64): int64 {.magic: "BitorI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `or`(x, y: uint): uint {.magic: "BitorI", noSideEffect, ...raises: [], tags: [].}
- Computes the bitwise or of numbers x and y. Source Edit
proc `or`(x, y: uint8): uint8 {.magic: "BitorI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `or`(x, y: uint16): uint16 {.magic: "BitorI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `or`(x, y: uint32): uint32 {.magic: "BitorI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `or`(x, y: uint64): uint64 {.magic: "BitorI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `shl`(x: int8; y: SomeInteger): int8 {.magic: "ShlI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `shl`(x: int16; y: SomeInteger): int16 {.magic: "ShlI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `shl`(x: int32; y: SomeInteger): int32 {.magic: "ShlI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `shl`(x: int64; y: SomeInteger): int64 {.magic: "ShlI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `shl`(x: int; y: SomeInteger): int {.magic: "ShlI", noSideEffect, ...raises: [], tags: [].}
-
Computes the shift left operation of x and y.
Note: Operator precedence is different than in C.
Example:
assert 1'i32 shl 4 == 0x0000_0010 assert 1'i64 shl 4 == 0x0000_0000_0000_0010
Source Edit proc `shl`(x: uint8; y: SomeInteger): uint8 {.magic: "ShlI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `shl`(x: uint16; y: SomeInteger): uint16 {.magic: "ShlI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `shl`(x: uint32; y: SomeInteger): uint32 {.magic: "ShlI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `shl`(x: uint64; y: SomeInteger): uint64 {.magic: "ShlI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `shl`(x: uint; y: SomeInteger): uint {.magic: "ShlI", noSideEffect, ...raises: [], tags: [].}
- Computes the shift left operation of x and y. Source Edit
proc `shr`(x: int8; y: SomeInteger): int8 {.magic: "AshrI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `shr`(x: int16; y: SomeInteger): int16 {.magic: "AshrI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `shr`(x: int32; y: SomeInteger): int32 {.magic: "AshrI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `shr`(x: int64; y: SomeInteger): int64 {.magic: "AshrI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `shr`(x: int; y: SomeInteger): int {.magic: "AshrI", noSideEffect, ...raises: [], tags: [].}
-
Computes the shift right operation of x and y, filling vacant bit positions with the sign bit.
Note: Operator precedence is different than in C.
See also:
- ashr func for arithmetic shift right
Example:
assert 0b0001_0000'i8 shr 2 == 0b0000_0100'i8 assert 0b0000_0001'i8 shr 1 == 0b0000_0000'i8 assert 0b1000_0000'i8 shr 4 == 0b1111_1000'i8 assert -1 shr 5 == -1 assert 1 shr 5 == 0 assert 16 shr 2 == 4 assert -16 shr 2 == -4
Source Edit proc `shr`(x: uint8; y: SomeInteger): uint8 {.magic: "ShrI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `shr`(x: uint16; y: SomeInteger): uint16 {.magic: "ShrI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `shr`(x: uint32; y: SomeInteger): uint32 {.magic: "ShrI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `shr`(x: uint64; y: SomeInteger): uint64 {.magic: "ShrI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `shr`(x: uint; y: SomeInteger): uint {.magic: "ShrI", noSideEffect, ...raises: [], tags: [].}
- Computes the shift right operation of x and y. Source Edit
proc `xor`(x, y: bool): bool {.magic: "Xor", noSideEffect, ...raises: [], tags: [].}
- Boolean exclusive or; returns true if x != y (if either argument is true while the other is false). Source Edit
proc `xor`(x, y: int): int {.magic: "BitxorI", noSideEffect, ...raises: [], tags: [].}
-
Computes the bitwise xor of numbers x and y.
Example:
assert (0b0011 xor 0b0101) == 0b0110 assert (0b0111 xor 0b1100) == 0b1011
Source Edit proc `xor`(x, y: int8): int8 {.magic: "BitxorI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `xor`(x, y: int16): int16 {.magic: "BitxorI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `xor`(x, y: int32): int32 {.magic: "BitxorI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `xor`(x, y: int64): int64 {.magic: "BitxorI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `xor`(x, y: uint): uint {.magic: "BitxorI", noSideEffect, ...raises: [], tags: [].}
- Computes the bitwise xor of numbers x and y. Source Edit
proc `xor`(x, y: uint8): uint8 {.magic: "BitxorI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `xor`(x, y: uint16): uint16 {.magic: "BitxorI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `xor`(x, y: uint32): uint32 {.magic: "BitxorI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc `xor`(x, y: uint64): uint64 {.magic: "BitxorI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
func abs(x: int64): int64 {.magic: "AbsI", inline, ...raises: [], tags: [].}
-
Returns the absolute value of x.
If x is low(x) (that is -MININT for its type), an overflow exception is thrown (if overflow checking is turned on).
Source Edit proc add(x: var cstring; y: cstring) {.magic: "AppendStrStr", ...raises: [], tags: [].}
-
Appends y to x in place. Only implemented for JS backend.
Example:
when defined(js): var tmp: cstring = "" tmp.add(cstring("ab")) tmp.add(cstring("cd")) doAssert tmp == cstring("abcd")
Source Edit proc add(x: var string; y: char) {.magic: "AppendStrCh", noSideEffect, ...raises: [], tags: [].}
-
Appends y to x in place.
var tmp = "" tmp.add('a') tmp.add('b') assert(tmp == "ab")
Source Edit proc add(x: var string; y: cstring) {.asmNoStackFrame, ...raises: [], tags: [].}
-
Appends y to x in place.
Example:
var tmp = "" tmp.add(cstring("ab")) tmp.add(cstring("cd")) doAssert tmp == "abcd"
Source Edit proc add(x: var string; y: string) {.magic: "AppendStrStr", noSideEffect, ...raises: [], tags: [].}
-
Concatenates x and y in place.
See also strbasics.add.
Example:
var tmp = "" tmp.add("ab") tmp.add("cd") assert tmp == "abcd"
Source Edit proc add[T](x: var seq[T]; value: sink T) {.magic: "AppendSeqElem", noSideEffect, nodestroy, ...raises: [], tags: [].}
-
Generic proc for adding a data item y to a container x.
For containers that have an order, add means append. New generic containers should also call their adding proc add for consistency. Generic code becomes much easier to write if the Nim naming scheme is respected.
Source Edit proc 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:
var s: seq[string] = @["test2","test2"] s.add("test") # s <- @[test2, test2, test]
Source Edit proc addEscapedChar(s: var string; c: char) {.noSideEffect, inline, ...raises: [], tags: [].}
-
Adds a char to string s and applies the following escaping:
- replaces any \ by \\
- replaces any ' by \'
- replaces any " by \"
- replaces any \a by \\a
- replaces any \b by \\b
- replaces any \t by \\t
- replaces any \n by \\n
- replaces any \v by \\v
- replaces any \f by \\f
- replaces any \r by \\r
- replaces any \e by \\e
- replaces any other character not in the set {\21..\126} by \xHH where HH is its hexadecimal value
The procedure has been designed so that its output is usable for many different common syntaxes.
Warning: This is not correct for producing ANSI C code!Source Edit proc addQuitProc(quitProc: proc () {.noconv.}) {.importc: "atexit", header: "<stdlib.h>", ...deprecated: "use exitprocs.addExitProc", raises: [], tags: [].}
-
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 proc addQuoted[T](s: var string; x: T)
-
Appends x to string s in place, applying quoting and escaping if x is a string or char.
See addEscapedChar for the escaping scheme. When x is a string, characters in the range {\128..\255} are never escaped so that multibyte UTF-8 characters are untouched (note that this behavior is different from addEscapedChar).
The Nim standard library uses this function on the elements of collections when producing a string representation of a collection. It is recommended to use this function as well for user-side collections. Users may overload addQuoted for custom (string-like) types if they want to implement a customized element representation.
var tmp = "" tmp.addQuoted(1) tmp.add(", ") tmp.addQuoted("string") tmp.add(", ") tmp.addQuoted('c') assert(tmp == """1, "string", 'c'""")
Source Edit proc alignof(x: typedesc): int {.magic: "AlignOf", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc alloc0Impl(size: Natural): pointer {.noconv, ...gcsafe, tags: [], gcsafe, locks: 0, ...raises: [].}
- Source Edit
proc allocCStringArray(a: openArray[string]): cstringArray {....raises: [], tags: [].}
- Creates a NULL terminated cstringArray from a. The result has to be freed with deallocCStringArray after it's not needed anymore. Source Edit
proc allocImpl(size: Natural): pointer {.noconv, ...gcsafe, tags: [], gcsafe, locks: 0, ...raises: [].}
- Source Edit
proc ashr(x: int8; y: SomeInteger): int8 {.magic: "AshrI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc ashr(x: int16; y: SomeInteger): int16 {.magic: "AshrI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc ashr(x: int32; y: SomeInteger): int32 {.magic: "AshrI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc ashr(x: int64; y: SomeInteger): int64 {.magic: "AshrI", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc ashr(x: int; y: SomeInteger): int {.magic: "AshrI", noSideEffect, ...raises: [], tags: [].}
-
Shifts right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off.
Note that ashr is not an operator so use the normal function call syntax for it.
See also:
Example:
assert ashr(0b0001_0000'i8, 2) == 0b0000_0100'i8 assert ashr(0b1000_0000'i8, 8) == 0b1111_1111'i8 assert ashr(0b1000_0000'i8, 1) == 0b1100_0000'i8
Source Edit proc astToStr[T](x: T): string {.magic: "AstToStr", noSideEffect, ...raises: [], tags: [].}
- Converts the AST of x into a string representation. This is very useful for debugging. Source Edit
proc atomicAddFetch[T: AtomType](p: ptr T; val: T; mem: AtomMemModel): T {. importc: "__atomic_add_fetch", nodecl, ...raises: [], tags: [].}
- Source Edit
proc atomicAlwaysLockFree(size: int; p: pointer): bool {. importc: "__atomic_always_lock_free", nodecl, ...raises: [], tags: [].}
- This built-in function returns true if objects of size bytes always generate lock free atomic instructions for the target architecture. size must resolve to a compile-time constant and the result also resolves to a compile-time constant. ptr is an optional pointer to the object that may be used to determine alignment. A value of 0 indicates typical alignment should be used. The compiler may also ignore this parameter. Source Edit
proc atomicAndFetch[T: AtomType](p: ptr T; val: T; mem: AtomMemModel): T {. importc: "__atomic_and_fetch", nodecl, ...raises: [], tags: [].}
- Source Edit
proc atomicClear(p: pointer; mem: AtomMemModel) {.importc: "__atomic_clear", nodecl, ...raises: [], tags: [].}
- This built-in function performs an atomic clear operation at p. After the operation, at p contains 0. ATOMIC_RELAXED, ATOMIC_SEQ_CST, ATOMIC_RELEASE Source Edit
proc atomicCompareExchange[T: AtomType](p, expected, desired: ptr T; weak: bool; success_memmodel: AtomMemModel; failure_memmodel: AtomMemModel): bool {. importc: "__atomic_compare_exchange", nodecl, ...raises: [], tags: [].}
- This proc implements the generic version of atomic_compare_exchange. The proc is virtually identical to atomic_compare_exchange_n, except the desired value is also a pointer. Source Edit
proc atomicCompareExchangeN[T: AtomType](p, expected: ptr T; desired: T; weak: bool; success_memmodel: AtomMemModel; failure_memmodel: AtomMemModel): bool {. importc: "__atomic_compare_exchange_n", nodecl, ...raises: [], tags: [].}
- This proc implements an atomic compare and exchange operation. This compares the contents at p with the contents at expected and if equal, writes desired at p. If they are not equal, the current contents at p is written into expected. Weak is true for weak compare_exchange, and false for the strong variation. Many targets only offer the strong variation and ignore the parameter. When in doubt, use the strong variation. True is returned if desired is written at p and the execution is considered to conform to the memory model specified by success_memmodel. There are no restrictions on what memory model can be used here. False is returned otherwise, and the execution is considered to conform to failure_memmodel. This memory model cannot be __ATOMIC_RELEASE nor __ATOMIC_ACQ_REL. It also cannot be a stronger model than that specified by success_memmodel. Source Edit
proc atomicDec(memLoc: var int; x: int = 1; order = ATOMIC_RELAXED): int {. ...raises: [], tags: [].}
- Atomic decrement of memLoc. Returns the value after the operation. Source Edit
proc atomicExchange[T: AtomType](p, val, ret: ptr T; mem: AtomMemModel) {. importc: "__atomic_exchange", nodecl, ...raises: [], tags: [].}
- This is the generic version of an atomic exchange. It stores the contents at val at p. The original value at p is copied into ret. Source Edit
proc atomicExchangeN[T: AtomType](p: ptr T; val: T; mem: AtomMemModel): T {. importc: "__atomic_exchange_n", nodecl, ...raises: [], tags: [].}
- This proc implements an atomic exchange operation. It writes val at p, and returns the previous contents at p. ATOMIC_RELAXED, ATOMIC_SEQ_CST, ATOMIC_ACQUIRE, ATOMIC_RELEASE, ATOMIC_ACQ_REL Source Edit
proc atomicFetchAdd[T: AtomType](p: ptr T; val: T; mem: AtomMemModel): T {. importc: "__atomic_fetch_add", nodecl, ...raises: [], tags: [].}
- Source Edit
proc atomicFetchAnd[T: AtomType](p: ptr T; val: T; mem: AtomMemModel): T {. importc: "__atomic_fetch_and", nodecl, ...raises: [], tags: [].}
- Source Edit
proc atomicFetchNand[T: AtomType](p: ptr T; val: T; mem: AtomMemModel): T {. importc: "__atomic_fetch_nand", nodecl, ...raises: [], tags: [].}
- Source Edit
proc atomicFetchOr[T: AtomType](p: ptr T; val: T; mem: AtomMemModel): T {. importc: "__atomic_fetch_or", nodecl, ...raises: [], tags: [].}
- Source Edit
proc atomicFetchSub[T: AtomType](p: ptr T; val: T; mem: AtomMemModel): T {. importc: "__atomic_fetch_sub", nodecl, ...raises: [], tags: [].}
- Source Edit
proc atomicFetchXor[T: AtomType](p: ptr T; val: T; mem: AtomMemModel): T {. importc: "__atomic_fetch_xor", nodecl, ...raises: [], tags: [].}
- Source Edit
proc atomicInc(memLoc: var int; x: int = 1; order = ATOMIC_RELAXED): int {. ...raises: [], tags: [].}
- Atomic increment of memLoc. Returns the value after the operation. Source Edit
proc atomicIsLockFree(size: int; p: pointer): bool {. importc: "__atomic_is_lock_free", nodecl, ...raises: [], tags: [].}
- This built-in function returns true if objects of size bytes always generate lock free atomic instructions for the target architecture. If it is not known to be lock free a call is made to a runtime routine named __atomic_is_lock_free. ptr is an optional pointer to the object that may be used to determine alignment. A value of 0 indicates typical alignment should be used. The compiler may also ignore this parameter. Source Edit
proc atomicLoad[T: AtomType](p, ret: ptr T; mem: AtomMemModel) {. importc: "__atomic_load", nodecl, ...raises: [], tags: [].}
- This is the generic version of an atomic load. It returns the contents at p in ret. Source Edit
proc atomicLoadN[T: AtomType](p: ptr T; mem: AtomMemModel): T {. importc: "__atomic_load_n", nodecl, ...raises: [], tags: [].}
- This proc implements an atomic load operation. It returns the contents at p. ATOMIC_RELAXED, ATOMIC_SEQ_CST, ATOMIC_ACQUIRE, ATOMIC_CONSUME. Source Edit
proc atomicNandFetch[T: AtomType](p: ptr T; val: T; mem: AtomMemModel): T {. importc: "__atomic_nand_fetch", nodecl, ...raises: [], tags: [].}
- Source Edit
proc atomicOrFetch[T: AtomType](p: ptr T; val: T; mem: AtomMemModel): T {. importc: "__atomic_or_fetch", nodecl, ...raises: [], tags: [].}
- Source Edit
proc atomicSignalFence(mem: AtomMemModel) {.importc: "__atomic_signal_fence", nodecl, ...raises: [], tags: [].}
- This built-in function acts as a synchronization fence between a thread and signal handlers based in the same thread. All memory orders are valid. Source Edit
proc atomicStore[T: AtomType](p, val: ptr T; mem: AtomMemModel) {. importc: "__atomic_store", nodecl, ...raises: [], tags: [].}
- This is the generic version of an atomic store. It stores the value of val at p Source Edit
proc atomicStoreN[T: AtomType](p: ptr T; val: T; mem: AtomMemModel) {. importc: "__atomic_store_n", nodecl, ...raises: [], tags: [].}
- This proc implements an atomic store operation. It writes val at p. ATOMIC_RELAXED, ATOMIC_SEQ_CST, and ATOMIC_RELEASE. Source Edit
proc atomicSubFetch[T: AtomType](p: ptr T; val: T; mem: AtomMemModel): T {. importc: "__atomic_sub_fetch", nodecl, ...raises: [], tags: [].}
- Source Edit
proc atomicTestAndSet(p: pointer; mem: AtomMemModel): bool {. importc: "__atomic_test_and_set", nodecl, ...raises: [], tags: [].}
- This built-in function performs an atomic test-and-set operation on the byte at p. The byte is set to some implementation defined nonzero "set" value and the return value is true if and only if the previous contents were "set". All memory models are valid. Source Edit
proc atomicThreadFence(mem: AtomMemModel) {.importc: "__atomic_thread_fence", nodecl, ...raises: [], tags: [].}
- This built-in function acts as a synchronization fence between threads based on the specified memory model. All memory orders are valid. Source Edit
proc atomicXorFetch[T: AtomType](p: ptr T; val: T; mem: AtomMemModel): T {. importc: "__atomic_xor_fetch", nodecl, ...raises: [], tags: [].}
- Source Edit
func card[T](x: set[T]): int {.magic: "Card", ...raises: [], tags: [].}
-
Returns the cardinality of the set x, i.e. the number of elements in the set.
Example:
var a = {1, 3, 5, 7} assert card(a) == 4 var b = {1, 3, 5, 7, 5} assert card(b) == 4 # repeated 5 doesn't count
Source Edit func chr(u: range[0 .. 255]): char {.magic: "Chr", ...raises: [], tags: [].}
-
Converts u to a char, same as char(u).
Example:
doAssert chr(65) == 'A' doAssert chr(255) == '\255' doAssert chr(255) == char(255) doAssert not compiles chr(256) doAssert not compiles char(256) var x = 256 doAssertRaises(RangeDefect): discard chr(x) doAssertRaises(RangeDefect): discard char(x)
Source Edit proc clamp[T](x, a, b: T): T
-
Limits the value x within the interval [a, b]. This proc is equivalent to but faster than max(a, min(b, x)).Warning: a <= b is assumed and will not be checked (currently).
See also: math.clamp for a version that takes a Slice[T] instead.
Example:
assert (1.4).clamp(0.0, 1.0) == 1.0 assert (0.5).clamp(0.0, 1.0) == 0.5 assert 4.clamp(1, 3) == max(1, min(3, 4))
Source Edit proc close[TMsg](c: var Channel[TMsg])
- Closes a channel c and frees its associated resources. Source Edit
proc cmp(x, y: string): int {.noSideEffect, ...raises: [], tags: [].}
-
Compare proc for strings. More efficient than the generic version.
Note: The precise result values depend on the used C runtime library and can differ between operating systems!
Source Edit proc cmp[T](x, y: T): int
-
Generic compare proc.
Returns:
- a value less than zero, if x < y
- a value greater than zero, if x > y
- zero, if x == y
This is useful for writing generic algorithms without performance loss. This generic implementation uses the == and < operators.
import std/algorithm echo sorted(@[4, 2, 6, 5, 8, 7], cmp[int])
Source Edit proc cmpMem(a, b: pointer; size: Natural): int {.inline, noSideEffect, ...tags: [], locks: 0, ...raises: [].}
-
Compares the memory blocks a and b. size bytes will be compared.
Returns:
- a value less than zero, if a < b
- a value greater than zero, if a > b
- zero, if a == b
Like any procedure dealing with raw memory this is unsafe.
Source Edit proc compileOption(option, arg: string): bool {.magic: "CompileOptionArg", noSideEffect, ...raises: [], tags: [].}
-
Can be used to determine an enum compile-time option.
See also:
- compileOption for on|off options
- defined
- std/compilesettings module
Example:
when compileOption("opt", "size") and compileOption("gc", "boehm"): discard "compiled with optimization for size and uses Boehm's GC"
Source Edit proc compileOption(option: string): bool {.magic: "CompileOption", noSideEffect, ...raises: [], tags: [].}
-
Can be used to determine an on|off compile-time option.
See also:
- compileOption for enum options
- defined
- std/compilesettings module
Example: cmd: --floatChecks:off
static: doAssert not compileOption("floatchecks") {.push floatChecks: on.} static: doAssert compileOption("floatchecks") # floating point NaN and Inf checks enabled in this scope {.pop.}
Source Edit proc compiles(x: untyped): bool {.magic: "Compiles", noSideEffect, compileTime, ...raises: [], tags: [].}
-
Special compile-time procedure that checks whether x can be compiled without any semantic error. This can be used to check whether a type supports some operation:
when compiles(3 + 4): echo "'+' for integers is available"
Source Edit proc contains[T](a: openArray[T]; item: T): bool {.inline.}
-
Returns true if item is in a or false if not found. This is a shortcut for find(a, item) >= 0.
This allows the in operator: a.contains(item) is the same as item in a.
var a = @[1, 3, 5] assert a.contains(5) assert 3 in a assert 99 notin a
Source Edit func contains[T](x: set[T]; y: T): bool {.magic: "InSet", ...raises: [], tags: [].}
-
One should overload this proc if one wants to overload the in operator.
The parameters are in reverse order! a in b is a template for contains(b, a). This is because the unification algorithm that Nim uses for overload resolution works from left to right. But for the in operator that would be the wrong direction for this piece of code:
Example:
var s: set[range['a'..'z']] = {'a'..'c'} assert s.contains('c') assert 'b' in s assert 'd' notin s assert set['a'..'z'] is set[range['a'..'z']]
If in had been declared as [T](elem: T, s: set[T]) then T would have been bound to char. But s is not compatible to type set[char]! The solution is to bind T to range['a'..'z']. This is achieved by reversing the parameters for contains; in then passes its arguments in reverse order. Source Edit proc contains[U, V, W](s: HSlice[U, V]; value: W): bool {.noSideEffect, inline.}
-
Checks if value is within the range of s; returns true if value >= s.a and value <= s.b
assert((1..3).contains(1) == true) assert((1..3).contains(2) == true) assert((1..3).contains(4) == false)
Source Edit proc copyMem(dest, source: pointer; size: Natural) {.inline, ...gcsafe, locks: 0, ...tags: [], locks: 0, ...raises: [].}
- Copies the contents from the memory at source to the memory at dest. Exactly size bytes will be copied. The memory regions may not overlap. Like any procedure dealing with raw memory this is unsafe. Source Edit
proc create(T: typedesc; size = 1.Positive): ptr T:type {.inline, ...gcsafe, locks: 0, ...raises: [].}
-
Allocates a new memory block with at least T.sizeof * size bytes.
The block has to be freed with resize(block, 0) or dealloc(block). The block is initialized with all bytes containing zero, so it is somewhat safer than createU.
The allocated memory belongs to its allocating thread! Use createShared to allocate from a shared heap.
Source Edit proc createThread(t: var Thread[void]; tp: proc () {.thread, nimcall.}) {. ...raises: [ResourceExhaustedError], tags: [RootEffect].}
- Source Edit
proc createThread[TArg](t: var Thread[TArg]; tp: proc (arg: TArg) {.thread, nimcall.}; param: TArg)
- Convenience short-hand for creating and assigning a thread in-place. Source Edit
proc createThread[TArg](tp: proc (arg: TArg) {.thread, nimcall.}; param: TArg): Thread[ TArg]
-
Creates a new thread, starts its execution, and returns a handle of the thread.
Entry point is the proc tp. param is passed to tp. TArg can be void if you don't need to pass any data to the thread.
Source Edit proc createU(T: typedesc; size = 1.Positive): ptr T:type {.inline, ...gcsafe, locks: 0, ...raises: [].}
-
Allocates a new memory block with at least T.sizeof * size bytes.
The block has to be freed with resize(block, 0) or dealloc(block). The block is not initialized, so reading from it before writing to it is undefined behaviour!
The allocated memory belongs to its allocating thread! Use createSharedU to allocate from a shared heap.
See also:
Source Edit proc cstringArrayToSeq(a: cstringArray): seq[string] {....raises: [], tags: [].}
- Converts a cstringArray to a seq[string]. a is supposed to be terminated by nil. Source Edit
proc cstringArrayToSeq(a: cstringArray; len: Natural): seq[string] {....raises: [], tags: [].}
- Converts a cstringArray to a seq[string]. a is supposed to be of length len. Source Edit
proc dealloc(p: pointer) {.noconv, compilerproc, ...gcsafe, gcsafe, locks: 0, ...raises: [], tags: [].}
-
Frees the memory allocated with alloc, alloc0, realloc, create or createU.
This procedure is dangerous! If one forgets to free the memory a leak occurs; if one tries to access freed memory (or just freeing it twice!) a core dump may happen or other memory may be corrupted.
The freed memory must belong to its allocating thread! Use deallocShared to deallocate from a shared heap.
Source Edit proc deallocCStringArray(a: cstringArray) {....raises: [], tags: [].}
- Frees a NULL terminated cstringArray. Source Edit
proc deallocImpl(p: pointer) {.noconv, ...gcsafe, tags: [], gcsafe, locks: 0, ...raises: [].}
- Source Edit
proc debugEcho(x: varargs[typed, `$`]) {.magic: "Echo", noSideEffect, ...tags: [], raises: [].}
- Same as echo, but as a special semantic rule, debugEcho pretends to be free of side effects, so that it can be used for debugging routines marked as noSideEffect. Source Edit
proc dec[T: Ordinal](x: var T; y = 1) {.magic: "Dec", noSideEffect, ...raises: [], tags: [].}
-
Decrements the ordinal x by y.
If such a value does not exist, OverflowDefect is raised or a compile time error occurs. This is a short notation for: x = pred(x, y).
Example:
var i = 2 dec(i) assert i == 1 dec(i, 3) assert i == -2
Source Edit proc declared(x: untyped): bool {.magic: "Declared", noSideEffect, compileTime, ...raises: [], tags: [].}
-
Special compile-time procedure that checks whether x is declared. x has to be an identifier or a qualified identifier.
See also:
This can be used to check whether a library provides a certain feature or not:
when not declared(strutils.toUpper): # provide our own toUpper proc here, because strutils is # missing it.
Source Edit proc declaredInScope(x: untyped): bool {.magic: "DeclaredInScope", noSideEffect, compileTime, ...raises: [], tags: [].}
- Special compile-time procedure that checks whether x is declared in the current scope. x has to be an identifier. Source Edit
proc deepCopy[T](x: var T; y: T) {.noSideEffect, magic: "DeepCopy", ...raises: [], tags: [].}
-
Performs a deep copy of y and copies it into x.
This was used by the code generator for the implementation of the now removed spawn feature.
For --gc:arc or --gc:orc deepcopy support has to be enabled via --deepcopy:on.
Source Edit proc default[T](_: typedesc[T]): T {.magic: "Default", noSideEffect, ...raises: [], tags: [].}
-
returns the default value of the type T.
Example:
assert (int, float).default == (0, 0.0) # note: `var a = default(T)` is usually the same as `var a: T` and (currently) generates # a value whose binary representation is all 0, regardless of whether this # would violate type constraints such as `range`, `not nil`, etc. This # property is required to implement certain algorithms efficiently which # may require intermediate invalid states. type Foo = object a: range[2..6] var a1: range[2..6] # currently, this compiles # var a2: Foo # currently, this errors: Error: The Foo type doesn't have a default value. # var a3 = Foo() # ditto var a3 = Foo.default # this works, but generates a `UnsafeDefault` warning.
Source Edit proc defined(x: untyped): bool {.magic: "Defined", noSideEffect, compileTime, ...raises: [], tags: [].}
-
Special compile-time procedure that checks whether x is defined.
See also:
- compileOption for on|off options
- compileOption for enum options
- define pragmas
x is an external symbol introduced through the compiler's -d:x switch to enable build time conditionals:
when not defined(release): # Do here programmer friendly expensive sanity checks. # Put here the normal code
Source Edit proc del[T](x: var seq[T]; i: Natural) {.noSideEffect.}
-
Deletes the item at index i by putting x[high(x)] into position i.
This is an O(1) operation.
See also:
- delete for preserving the order
Example:
var a = @[10, 11, 12, 13, 14] a.del(2) assert a == @[10, 11, 14, 13]
Source Edit proc delete[T](x: var seq[T]; i: Natural) {.noSideEffect.}
-
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:
var s = @[1, 2, 3, 4, 5] s.delete(2) doAssert s == @[1, 2, 4, 5]
Source Edit proc echo(x: varargs[typed, `$`]) {.magic: "Echo", ...gcsafe, locks: 0, sideEffect, ...raises: [], tags: [].}
-
Writes and flushes the parameters to the standard output.
Special built-in that takes a variable number of arguments. Each argument is converted to a string via $, so it works for user-defined types that have an overloaded $ operator. It is roughly equivalent to writeLine(stdout, x); flushFile(stdout), but available for the JavaScript target too.
Unlike other IO operations this is guaranteed to be thread-safe as echo is very often used for debugging convenience. If you want to use echo inside a proc without side effects you can use debugEcho instead.
Source Edit proc equalMem(a, b: pointer; size: Natural): bool {.inline, noSideEffect, ...tags: [], locks: 0, ...raises: [].}
-
Compares the memory blocks a and b. size bytes will be compared.
If the blocks are equal, true is returned, false otherwise. Like any procedure dealing with raw memory this is unsafe.
Source Edit func excl[T](x: var set[T]; y: T) {.magic: "Excl", ...raises: [], tags: [].}
-
Excludes element y from the set x.
This is the same as x = x - {y}, but it might be more efficient.
Example:
var b = {2, 3, 5, 6, 12, 545} b.excl(5) assert b == {2, 3, 6, 12, 545}
Source Edit proc find[T, S](a: T; item: S): int {.inline.}
- Returns the first index of item in a or -1 if not found. This requires appropriate items and == operations to work. Source Edit
proc finished[T: proc](x: T): bool {.noSideEffect, magic: "Finished", ...raises: [], tags: [].}
- Tests if the given closure iterator x has finished iterating. Source Edit
proc formatFieldDefect(f, discVal: sink string): string {....raises: [], tags: [].}
- Source Edit
proc GC_disableMarkAndSweep() {....raises: [], tags: [].}
- For --gc:orc an alias for GC_disableOrc. Source Edit
proc GC_disableOrc() {....raises: [], tags: [].}
- Disables the cycle collector subsystem of --gc:orc. This is a --gc:orc specific API. Check with when defined(gcOrc) for its existence. Source Edit
proc GC_enableMarkAndSweep() {....raises: [], tags: [].}
- For --gc:orc an alias for GC_enableOrc. Source Edit
proc GC_enableOrc() {....raises: [], tags: [].}
- Enables the cycle collector subsystem of --gc:orc. This is a --gc:orc specific API. Check with when defined(gcOrc) for its existence. Source Edit
proc GC_fullCollect() {....raises: [], tags: [RootEffect].}
- Forces a full garbage collection pass. With --gc:orc triggers the cycle collector. This is an alias for GC_runOrc. Source Edit
proc GC_getStatistics(): string {....raises: [], tags: [].}
- Source Edit
proc GC_partialCollect(limit: int) {....raises: [], tags: [RootEffect].}
- Source Edit
proc GC_prepareOrc(): int {.inline, ...raises: [], tags: [].}
- Source Edit
proc getAllocStats(): AllocStats {....raises: [], tags: [].}
- Source Edit
proc getCurrentException(): ref Exception {.compilerproc, inline, ...gcsafe, locks: 0, ...raises: [], tags: [].}
- Retrieves the current exception; if there is none, nil is returned. Source Edit
proc getCurrentExceptionMsg(): string {.inline, ...gcsafe, locks: 0, ...raises: [], tags: [].}
- Retrieves the error message that was attached to the current exception; if there is none, "" is returned. Source Edit
proc getFrameState(): FrameState {.compilerproc, inline, ...raises: [], tags: [].}
- Source Edit
proc getFreeMem(): int {....gcsafe, raises: [], tags: [].}
- Returns the number of bytes that are owned by the process, but do not hold any meaningful data. Source Edit
proc getGcFrame(): GcFrame {.compilerproc, inline, ...raises: [], tags: [].}
- Source Edit
proc getOccupiedMem(): int {....gcsafe, raises: [], tags: [].}
- Returns the number of bytes that are owned by the process and hold data. Source Edit
proc getStackTrace(): string {....gcsafe, raises: [], tags: [].}
- Gets the current stack trace. This only works for debug builds. Source Edit
proc getStackTrace(e: ref Exception): string {....gcsafe, raises: [], tags: [].}
- Gets the stack trace associated with e, which is the stack that lead to the raise statement. This only works for debug builds. Source Edit
proc getStackTraceEntries(): seq[StackTraceEntry] {....raises: [], tags: [].}
- Returns the stack trace entries for the current stack trace. This is not yet available for the JS backend. Source Edit
proc getStackTraceEntries(e: ref Exception): lent seq[StackTraceEntry] {. ...raises: [], tags: [].}
- Source Edit
proc getThreadId(): int {....raises: [], tags: [].}
- Gets the ID of the currently running thread. Source Edit
proc getTotalMem(): int {....gcsafe, raises: [], tags: [].}
- Returns the number of bytes that are owned by the process. Source Edit
proc getTypeInfo[T](x: T): pointer {.magic: "GetTypeInfo", ...gcsafe, locks: 0, ...raises: [], tags: [].}
-
Get type information for x.
Ordinary code should not use this, but the typeinfo module instead.
Source Edit proc gorge(command: string; input = ""; cache = ""): string {.compileTime, ...deprecated: "use staticExec", raises: [], tags: [].}
- staticExec. Source Edit This is an alias for
proc gorgeEx(command: string; input = ""; cache = ""): tuple[output: string, exitCode: int] {....raises: [], tags: [].}
- Similar to gorge but also returns the exit code. Source Edit
proc handle[TArg](t: Thread[TArg]): SysThread {.inline.}
- Returns the thread handle of t. Source Edit
proc high(x: cstring): int {.magic: "High", noSideEffect, ...raises: [], tags: [].}
-
Returns the highest possible index of a compatible string x. This is sometimes an O(n) operation.
See also:
Source Edit proc high(x: string): int {.magic: "High", noSideEffect, ...raises: [], tags: [].}
-
Returns the highest possible index of a string x.
See also:
var str = "Hello world!" high(str) # => 11
Source Edit proc high[I, T](x: array[I, T]): I {.magic: "High", noSideEffect, ...raises: [], tags: [].}
-
Returns the highest possible index of an array x.
For empty arrays, the return type is int.
See also:
var arr = [1, 2, 3, 4, 5, 6, 7] high(arr) # => 6 for i in low(arr)..high(arr): echo arr[i]
Source Edit proc high[I, T](x: typedesc[array[I, T]]): I {.magic: "High", noSideEffect, ...raises: [], tags: [].}
-
Returns the highest possible index of an array type.
For empty arrays, the return type is int.
See also:
high(array[7, int]) # => 6
Source Edit proc high[T: Ordinal | enum | range](x: T): T {.magic: "High", noSideEffect, ...deprecated: "Deprecated since v1.4; there should not be `high(value)`. Use `high(type)`.", raises: [], tags: [].}
-
Returns the highest possible value of an ordinal value x.
As a special semantic rule, x may also be a type identifier.
This proc is deprecated, use this one instead:
high(2) # => 9223372036854775807
Source Edit proc high[T: Ordinal | enum | range](x: typedesc[T]): T {.magic: "High", noSideEffect, ...raises: [], tags: [].}
-
Returns the highest possible value of an ordinal or enum type.
high(int) is Nim's way of writing INT_MAX or MAX_INT.
See also:
high(int) # => 9223372036854775807
Source Edit proc high[T](x: openArray[T]): int {.magic: "High", noSideEffect, ...raises: [], tags: [].}
-
Returns the highest possible index of a sequence x.
See also:
var s = @[1, 2, 3, 4, 5, 6, 7] high(s) # => 6 for i in low(s)..high(s): echo s[i]
Source Edit proc inc[T: Ordinal](x: var T; y = 1) {.magic: "Inc", noSideEffect, ...raises: [], tags: [].}
-
Increments the ordinal x by y.
If such a value does not exist, OverflowDefect is raised or a compile time error occurs. This is a short notation for: x = succ(x, y).
Example:
var i = 2 inc(i) assert i == 3 inc(i, 3) assert i == 6
Source Edit func incl[T](x: var set[T]; y: T) {.magic: "Incl", ...raises: [], tags: [].}
-
Includes element y in the set x.
This is the same as x = x + {y}, but it might be more efficient.
Example:
var a = {1, 3, 5} a.incl(2) assert a == {1, 2, 3, 5} a.incl(4) assert a == {1, 2, 3, 4, 5}
Source Edit proc insert(x: var string; item: string; i = 0.Natural) {.noSideEffect, ...raises: [], tags: [].}
-
Inserts item into x at position i.
var a = "abc" a.insert("zz", 0) # a <- "zzabc"
Source Edit proc insert[T](x: var seq[T]; item: sink T; i = 0.Natural) {.noSideEffect.}
-
Inserts item into x at position i.
var i = @[1, 3, 5] i.insert(99, 0) # i <- @[99, 1, 3, 5]
Source Edit proc instantiationInfo(index = -1; fullPaths = false): tuple[filename: string, line: int, column: int] {.magic: "InstantiationInfo", noSideEffect, ...raises: [], tags: [].}
-
Provides access to the compiler's instantiation stack line information of a template.
While similar to the caller info of other languages, it is determined at compile time.
This proc is mostly useful for meta programming (eg. assert template) to retrieve information about the current filename and line number. Example:
import std/strutils template testException(exception, code: untyped): typed = try: let pos = instantiationInfo() discard(code) echo "Test failure at $1:$2 with '$3'" % [pos.filename, $pos.line, astToStr(code)] assert false, "A test expecting failure succeeded?" except exception: discard proc tester(pos: int): int = let a = @[1, 2, 3] result = a[pos] when isMainModule: testException(IndexDefect, tester(30)) testException(IndexDefect, tester(1)) # --> Test failure at example.nim:20 with 'tester(1)'
Source Edit proc isNil(x: string): bool {.noSideEffect, magic: "IsNil", error, ...raises: [], tags: [].}
- See also: Source Edit
proc isNil[T: proc](x: T): bool {.noSideEffect, magic: "IsNil", ...raises: [], tags: [].}
- Fast check whether x is nil. This is sometimes more efficient than == nil. Source Edit
proc isNil[T](x: seq[T]): bool {.noSideEffect, magic: "IsNil", error, ...raises: [], tags: [].}
-
Seqs are no longer nil by default, but set and empty. Check for zero length instead.
See also:
Source Edit proc iterToProc(iter: typed; envType: typedesc; procName: untyped) {. magic: "Plugin", compileTime, ...raises: [], tags: [].}
- Source Edit
proc joinThread[TArg](t: Thread[TArg]) {.inline.}
- Waits for the thread t to finish. Source Edit
proc joinThreads[TArg](t: varargs[Thread[TArg]])
- Waits for every thread in t to finish. Source Edit
func len(x: (type array) | array): int {.magic: "LengthArray", ...raises: [], tags: [].}
-
Returns the length of an array or an array type. This is roughly the same as high(T)-low(T)+1.
Example:
var a = [1, 1, 1] assert a.len == 3 assert array[0, float].len == 0 static: assert array[-2..2, float].len == 5
Source Edit proc len(x: cstring): int {.magic: "LengthStr", noSideEffect, ...raises: [], tags: [].}
-
Returns the length of a compatible string. This is an O(n) operation except in js at runtime.
Note: On the JS backend this currently counts UTF-16 code points instead of bytes at runtime (not at compile time). For now, if you need the byte length of the UTF-8 encoding, convert to string with $ first then call len.
Example:
doAssert len(cstring"abc") == 3 doAssert len(cstring r"ab\0c") == 5 # \0 is escaped doAssert len(cstring"ab\0c") == 5 # \0 is escaped var a: cstring = "ab\0c" when defined(js): doAssert a.len == 4 # len ignores \0 for js else: doAssert a.len == 2 # \0 is a null terminator static: var a2: cstring = "ab\0c" doAssert a2.len == 2 # \0 is a null terminator, even in js vm
Source Edit func len(x: string): int {.magic: "LengthStr", ...raises: [], tags: [].}
-
Returns the length of a string.
Example:
assert "abc".len == 3 assert "".len == 0 assert string.default.len == 0
Source Edit func len[T](x: seq[T]): int {.magic: "LengthSeq", ...raises: [], tags: [].}
-
Returns the length of x.
Example:
assert @[0, 1].len == 2 assert seq[int].default.len == 0 assert newSeq[int](3).len == 3 let s = newSeqOfCap[int](3) assert s.len == 0
Source Edit func len[T](x: set[T]): int {.magic: "Card", ...raises: [], tags: [].}
- An alias for card(x). Source Edit
func len[TOpenArray: openArray | varargs](x: TOpenArray): int {. magic: "LengthOpenArray", ...raises: [], tags: [].}
-
Returns the length of an openArray.
Example:
proc bar[T](a: openArray[T]): int = len(a) assert bar([1,2]) == 2 assert [1,2].len == 2
Source Edit proc len[U: Ordinal; V: Ordinal](x: HSlice[U, V]): int {.noSideEffect, inline.}
-
Length of ordinal slice. When x.b < x.a returns zero length.
assert((0..5).len == 6) assert((5..2).len == 0)
Source Edit proc locals(): RootObj {.magic: "Plugin", noSideEffect, ...raises: [], tags: [].}
-
Generates a tuple constructor expression listing all the local variables in the current scope.
This is quite fast as it does not rely on any debug or runtime information. Note that in contrast to what the official signature says, the return type is not RootObj but a tuple of a structure that depends on the current scope. Example:
proc testLocals() = var a = "something" b = 4 c = locals() d = "super!" b = 1 for name, value in fieldPairs(c): echo "name ", name, " with value ", value echo "B is ", b # -> name a with value something # -> name b with value 4 # -> B is 1
Source Edit proc low(x: cstring): int {.magic: "Low", noSideEffect, ...raises: [], tags: [].}
-
Returns the lowest possible index of a compatible string x.
See also:
Source Edit proc low(x: string): int {.magic: "Low", noSideEffect, ...raises: [], tags: [].}
-
Returns the lowest possible index of a string x.
See also:
var str = "Hello world!" low(str) # => 0
Source Edit proc low[I, T](x: array[I, T]): I {.magic: "Low", noSideEffect, ...raises: [], tags: [].}
-
Returns the lowest possible index of an array x.
For empty arrays, the return type is int.
See also:
var arr = [1, 2, 3, 4, 5, 6, 7] low(arr) # => 0 for i in low(arr)..high(arr): echo arr[i]
Source Edit proc low[I, T](x: typedesc[array[I, T]]): I {.magic: "Low", noSideEffect, ...raises: [], tags: [].}
-
Returns the lowest possible index of an array type.
For empty arrays, the return type is int.
See also:
low(array[7, int]) # => 0
Source Edit proc low[T: Ordinal | enum | range](x: T): T {.magic: "Low", noSideEffect, ...deprecated: "Deprecated since v1.4; there should not be `low(value)`. Use `low(type)`.", raises: [], tags: [].}
-
Returns the lowest possible value of an ordinal value x. As a special semantic rule, x may also be a type identifier.
This proc is deprecated, use this one instead:
low(2) # => -9223372036854775808
Source Edit proc low[T: Ordinal | enum | range](x: typedesc[T]): T {.magic: "Low", noSideEffect, ...raises: [], tags: [].}
-
Returns the lowest possible value of an ordinal or enum type.
low(int) is Nim's way of writing INT_MIN or MIN_INT.
See also:
low(int) # => -9223372036854775808
Source Edit proc low[T](x: openArray[T]): int {.magic: "Low", noSideEffect, ...raises: [], tags: [].}
-
Returns the lowest possible index of a sequence x.
See also:
var s = @[1, 2, 3, 4, 5, 6, 7] low(s) # => 0 for i in low(s)..high(s): echo s[i]
Source Edit proc max(x, y: int64): int64 {.magic: "MaxI", noSideEffect, ...raises: [], tags: [].}
- The maximum value of two integers. Source Edit
proc min(x, y: int64): int64 {.magic: "MinI", noSideEffect, ...raises: [], tags: [].}
- The minimum value of two integers. Source Edit
proc moveMem(dest, source: pointer; size: Natural) {.inline, ...gcsafe, locks: 0, ...tags: [], locks: 0, ...raises: [].}
-
Copies the contents from the memory at source to the memory at dest.
Exactly size bytes will be copied. The memory regions may overlap, moveMem handles this case appropriately and is thus somewhat more safe than copyMem. Like any procedure dealing with raw memory this is still unsafe, though.
Source Edit proc new(t: typedesc): auto
-
Creates a new object of type T and returns a safe (traced) reference to it as result value.
When T is a ref type then the resulting type will be T, otherwise it will be ref T.
Source Edit proc 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.
See also:
var inputStrings = newSeq[string](3) assert len(inputStrings) == 3 inputStrings[0] = "The fourth" inputStrings[1] = "assignment" inputStrings[2] = "would crash" #inputStrings[3] = "out of bounds"
Source Edit proc newSeq[T](s: var seq[T]; len: Natural) {.magic: "NewSeq", noSideEffect, ...raises: [], tags: [].}
-
Creates a new sequence of type seq[T] with length len.
This is equivalent to s = @[]; setlen(s, len), but more efficient since no reallocation is needed.
Note that the sequence will be filled with zeroed entries. After the creation of the sequence you should assign entries to the sequence instead of adding them. Example:
var inputStrings: seq[string] newSeq(inputStrings, 3) assert len(inputStrings) == 3 inputStrings[0] = "The fourth" inputStrings[1] = "assignment" inputStrings[2] = "would crash" #inputStrings[3] = "out of bounds"
Source Edit proc newSeqOfCap[T](cap: Natural): seq[T] {.magic: "NewSeqOfCap", noSideEffect, ...raises: [], tags: [].}
-
Creates a new sequence of type seq[T] with length zero and capacity cap.
var x = newSeqOfCap[int](5) assert len(x) == 0 x.add(10) assert len(x) == 1
Source Edit 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.
var x = newSeqUninitialized[int](3) assert len(x) == 3 x[0] = 10
Source Edit proc newString(len: Natural): string {.magic: "NewString", importc: "mnewString", noSideEffect, ...raises: [], tags: [].}
-
Returns a new string of length len but with uninitialized content. One needs to fill the string character after character with the index operator s[i].
This procedure exists only for optimization purposes; the same effect can be achieved with the & operator or with add.
Source Edit proc newStringOfCap(cap: Natural): string {.magic: "NewStringOfCap", importc: "rawNewString", noSideEffect, ...raises: [], tags: [].}
-
Returns a new string of length 0 but with capacity cap.
This procedure exists only for optimization purposes; the same effect can be achieved with the & operator or with add.
Source Edit proc onThreadDestruction(handler: proc () {.closure, ...gcsafe, raises: [].}) {. ...raises: [], tags: [RootEffect].}
-
Registers a thread local handler that is called at the thread's destruction.
A thread is destructed when the .thread proc returns normally or when it raises an exception. Note that unhandled exceptions in a thread nevertheless cause the whole process to die.
Source Edit proc 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 func ord[T: Ordinal | enum](x: T): int {.magic: "Ord", ...raises: [], tags: [].}
-
Returns the internal int value of x, including for enum with holes and distinct ordinal types.
Example:
assert ord('A') == 65 type Foo = enum f0 = 0, f1 = 3 assert f1.ord == 3 type Bar = distinct int assert 3.Bar.ord == 3
Source Edit proc 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 proc pinToCpu[Arg](t: var Thread[Arg]; cpu: Natural)
-
Pins a thread to a CPU.
In other words sets a thread's affinity. If you don't know what this means, you shouldn't use this proc.
Source Edit proc 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.
Example:
var a = @[1, 3, 5, 7] let b = pop(a) assert b == 7 assert a == @[1, 3, 5]
Source Edit proc popGcFrame() {.compilerproc, inline, ...raises: [], tags: [].}
- Source Edit
proc pred[T: Ordinal](x: T; y = 1): T {.magic: "Pred", noSideEffect, ...raises: [], tags: [].}
-
Returns the y-th predecessor (default: 1) of the value x.
If such a value does not exist, OverflowDefect is raised or a compile time error occurs.
Example:
assert pred(5) == 4 assert pred(5, 3) == 2
Source Edit proc prepareMutation(s: var string) {.inline, ...raises: [], tags: [].}
- Source Edit
proc procCall(x: untyped) {.magic: "ProcCall", compileTime, ...raises: [], tags: [].}
-
Special magic to prohibit dynamic binding for method calls. This is similar to super in ordinary OO languages.
# 'someMethod' will be resolved fully statically: procCall someMethod(a, b)
Source Edit proc pushGcFrame(s: GcFrame) {.compilerproc, inline, ...raises: [], tags: [].}
- Source Edit
proc quit(errorcode: int = QuitSuccess) {.magic: "Exit", noreturn, ...raises: [], tags: [].}
-
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.
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 proc quit(errormsg: string; errorcode = QuitFailure) {.noreturn, ...raises: [], tags: [].}
- A shorthand for echo(errormsg); quit(errorcode). Source Edit
proc rawEnv[T: proc](x: T): pointer {.noSideEffect, inline.}
- Retrieves the raw environment pointer of the closure x. See also rawProc. Source Edit
proc rawProc[T: proc](x: T): pointer {.noSideEffect, inline.}
- Retrieves the raw proc pointer of the closure x. This is useful for interfacing closures with C, hash compuations, etc. Source Edit
proc ready[TMsg](c: var Channel[TMsg]): bool
- Returns true if some thread is waiting on the channel c for new messages. Source Edit
proc realloc0Impl(p: pointer; oldSize, newSize: Natural): pointer {.noconv, ...gcsafe, tags: [], gcsafe, locks: 0, ...raises: [].}
- Source Edit
proc reallocImpl(p: pointer; newSize: Natural): pointer {.noconv, ...gcsafe, tags: [], gcsafe, locks: 0, ...raises: [].}
- Source Edit
proc recv[TMsg](c: var Channel[TMsg]): TMsg
-
Receives a message from the channel c.
This blocks until a message has arrived! You may use peek proc to avoid the blocking.
Source Edit proc resize[T](p: ptr T; newSize: Natural): ptr T {.inline, ...gcsafe, locks: 0, ...raises: [].}
-
Grows or shrinks a given memory block.
If p is nil then a new memory block is returned. In either way the block has at least T.sizeof * newSize bytes. If newSize == 0 and p is not nil resize calls dealloc(p). In other cases the block has to be freed with free.
The allocated memory belongs to its allocating thread! Use resizeShared to reallocate from a shared heap.
Source Edit proc runnableExamples(rdoccmd = ""; body: untyped) {.magic: "RunnableExamples", ...raises: [], tags: [].}
-
A section you should use to mark runnable example code with.
- In normal debug and release builds code within a runnableExamples section is ignored.
- The documentation generator is aware of these examples and considers them part of the ## doc comment. As the last step of documentation generation each runnableExample is put in its own file $file_examples$i.nim, compiled and tested. The collected examples are put into their own module to ensure the examples do not refer to non-exported symbols.
Example:
proc timesTwo*(x: int): int = ## This proc doubles a number. runnableExamples: # at module scope const exported* = 123 assert timesTwo(5) == 10 block: # at block scope defer: echo "done" runnableExamples "-d:foo -b:c": import std/compilesettings assert querySetting(backend) == "c" assert defined(foo) runnableExamples "-r:off": ## this one is only compiled import std/browsers openDefaultBrowser "https://forum.nim-lang.org/" 2 * x
Source Edit proc send[TMsg](c: var Channel[TMsg]; msg: sink TMsg) {.inline.}
- Sends a message to a thread. msg is deeply copied. Source Edit
proc setControlCHook(hook: proc () {.noconv.}) {....raises: [], tags: [].}
-
Allows you to override the behaviour of your application when CTRL+C is pressed. Only one such hook is supported. Example:
proc ctrlc() {.noconv.} = echo "Ctrl+C fired!" # do clean up stuff quit() setControlCHook(ctrlc)
Source Edit proc setCurrentException(exc: ref Exception) {.inline, ...gcsafe, locks: 0, ...raises: [], tags: [].}
-
Sets the current exception.Warning: Only use this if you know what you are doing.Source Edit
proc setFrameState(state: FrameState) {.compilerproc, inline, ...raises: [], tags: [].}
- Source Edit
proc setGcFrame(s: GcFrame) {.compilerproc, inline, ...raises: [], tags: [].}
- Source Edit
proc setLen(s: var string; newlen: Natural) {.magic: "SetLengthStr", noSideEffect, ...raises: [], tags: [].}
-
Sets the length of string s to newlen.
If the current length is greater than the new length, s will be truncated.
var myS = "Nim is great!!" myS.setLen(3) # myS <- "Nim" echo myS, " is fantastic!!"
Source Edit proc setLen[T](s: var seq[T]; newlen: Natural) {.magic: "SetLengthSeq", noSideEffect, ...raises: [], tags: [].}
-
Sets the length of seq s to newlen. T may be any sequence type.
If the current length is greater than the new length, s will be truncated.
var x = @[10, 20] x.setLen(5) x[4] = 50 assert x == @[10, 20, 0, 0, 50] x.setLen(1) assert x == @[10]
Source Edit proc shallowCopy[T](x: var T; y: T) {.noSideEffect, magic: "ShallowCopy", ...raises: [], tags: [].}
-
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 proc sizeof(x: typedesc): int {.magic: "SizeOf", noSideEffect, ...raises: [], tags: [].}
- Source Edit
proc sizeof[T](x: T): int {.magic: "SizeOf", noSideEffect, ...raises: [], tags: [].}
-
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, sizeof should fallback to the sizeof in the C compiler. The result isn't available for the Nim compiler and therefore can't be used inside of macros.
sizeof('A') # => 1 sizeof(2) # => 8
Source Edit proc slurp(filename: string): string {.compileTime, ...deprecated: "use staticRead", raises: [], tags: [].}
- staticRead. Source Edit This is an alias for
proc stackTraceAvailable(): bool {....raises: [], tags: [].}
- Source Edit
proc staticExec(command: string; input = ""; cache = ""): string {.compileTime, ...raises: [], tags: [].}
-
Executes an external process at compile-time and returns its text output (stdout + stderr).
If input is not an empty string, it will be passed as a standard input to the executed program.
const buildInfo = "Revision " & staticExec("git rev-parse HEAD") & "\nCompiled on " & staticExec("uname -v")
gorge is an alias for staticExec.
Note that you can use this proc inside a pragma like passc or passl.
If cache is not empty, the results of staticExec are cached within the nimcache directory. Use --forceBuild to get rid of this caching behaviour then. command & input & cache (the concatenated string) is used to determine whether the entry in the cache is still valid. You can use versioning information for cache:
const stateMachine = staticExec("dfaoptimizer", "input", "0.8.0")
Deprecate/Replace with variant that returns the exit code and output
Source Edit proc staticRead(filename: string): string {.compileTime, ...raises: [], tags: [].}
-
Compile-time readFile proc for easy resource embedding:
The maximum file size limit that staticRead and slurp can read is near or equal to the free memory of the device you are using to compile.
const myResource = staticRead"mydatafile.bin"
Source Edit proc substr(s: string; first, last: int): string {....raises: [], tags: [].}
-
Copies a slice of s into a new string and returns this new string.
The bounds first and last denote the indices of the first and last characters that shall be copied. If last is omitted, it is treated as high(s). If last >= s.len, s.len is used instead: This means substr can also be used to cut or limit a string's length.
Example:
let a = "abcdefgh" assert a.substr(2, 5) == "cdef" assert a.substr(2) == "cdefgh" assert a.substr(5, 99) == "fgh"
Source Edit proc succ[T: Ordinal](x: T; y = 1): T {.magic: "Succ", noSideEffect, ...raises: [], tags: [].}
-
Returns the y-th successor (default: 1) of the value x.
If such a value does not exist, OverflowDefect is raised or a compile time error occurs.
Example:
assert succ(5) == 6 assert succ(5, 3) == 8
Source Edit proc swap[T](a, b: var T) {.magic: "Swap", noSideEffect, ...raises: [], tags: [].}
-
Swaps the values a and b.
This is often more efficient than tmp = a; a = b; b = tmp. Particularly useful for sorting algorithms.
var a = 5 b = 9 swap(a, b) assert a == 9 assert b == 5
Source Edit proc toBiggestFloat(i: BiggestInt): BiggestFloat {.noSideEffect, inline, ...raises: [], tags: [].}
- Same as toFloat but for BiggestInt to BiggestFloat. Source Edit
proc toBiggestInt(f: BiggestFloat): BiggestInt {.noSideEffect, ...raises: [], tags: [].}
- Same as toInt but for BiggestFloat to BiggestInt. Source Edit
proc toFloat(i: int): float {.noSideEffect, inline, ...raises: [], tags: [].}
-
Converts an integer i into a float. Same as float(i).
If the conversion fails, ValueError is raised. However, on most platforms the conversion cannot fail.
let a = 2 b = 3.7 echo a.toFloat + b # => 5.7
Source Edit proc toInt(f: float): int {.noSideEffect, ...raises: [], tags: [].}
-
Converts a floating point number f into an int.
Conversion rounds f half away from 0, see Round half away from zero, as opposed to a type conversion which rounds towards zero.
Note that some floating point numbers (e.g. infinity or even 1e19) cannot be accurately converted.
doAssert toInt(0.49) == 0 doAssert toInt(0.5) == 1 doAssert toInt(-0.5) == -1 # rounding is symmetrical
Source Edit proc toOpenArray(x: cstring; first, last: int): openArray[char] {. magic: "Slice", ...raises: [], tags: [].}
- Source Edit
proc toOpenArray(x: string; first, last: int): openArray[char] {.magic: "Slice", ...raises: [], tags: [].}
- Source Edit
proc toOpenArray[I, T](x: array[I, T]; first, last: I): openArray[T] {. magic: "Slice", ...raises: [], tags: [].}
- Source Edit
proc toOpenArray[T](x: openArray[T]; first, last: int): openArray[T] {. magic: "Slice", ...raises: [], tags: [].}
- Source Edit
proc toOpenArray[T](x: ptr UncheckedArray[T]; first, last: int): openArray[T] {. magic: "Slice", ...raises: [], tags: [].}
- Source Edit
proc toOpenArray[T](x: seq[T]; first, last: int): openArray[T] {.magic: "Slice", ...raises: [], tags: [].}
- Source Edit
proc toOpenArrayByte(x: cstring; first, last: int): openArray[byte] {. magic: "Slice", ...raises: [], tags: [].}
- Source Edit
proc toOpenArrayByte(x: openArray[char]; first, last: int): openArray[byte] {. magic: "Slice", ...raises: [], tags: [].}
- Source Edit
proc toOpenArrayByte(x: seq[char]; first, last: int): openArray[byte] {. magic: "Slice", ...raises: [], tags: [].}
- Source Edit
proc toOpenArrayByte(x: string; first, last: int): openArray[byte] {. magic: "Slice", ...raises: [], tags: [].}
- Source Edit
proc toU8(x: int): int8 {....deprecated, raises: [], tags: [].}
- x as unsigned and converts it to a byte by taking the last 8 bits from x. Deprecated since version 0.19.9: Use unsigned integers instead. Source Edit treats
proc toU16(x: int): int16 {....deprecated, raises: [], tags: [].}
- x as unsigned and converts it to an int16 by taking the last 16 bits from x. Deprecated since version 0.19.9: Use unsigned integers instead. Source Edit treats
proc toU32(x: int64): int32 {....deprecated, raises: [], tags: [].}
- x as unsigned and converts it to an int32 by taking the last 32 bits from x. Deprecated since version 0.19.9: Use unsigned integers instead. Source Edit treats
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 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 proc typeof(x: untyped; mode = typeOfIter): typedesc {.magic: "TypeOf", noSideEffect, compileTime, ...raises: [], tags: [].}
-
Builtin typeof operation for accessing the type of an expression. Since version 0.20.0.
Example:
proc myFoo(): float = 0.0 iterator myFoo(): string = yield "abc" iterator myFoo2(): string = yield "abc" iterator myFoo3(): string {.closure.} = yield "abc" doAssert type(myFoo()) is string doAssert typeof(myFoo()) is string doAssert typeof(myFoo(), typeOfIter) is string doAssert typeof(myFoo3) is "iterator" doAssert typeof(myFoo(), typeOfProc) is float doAssert typeof(0.0, typeOfProc) is float doAssert typeof(myFoo3, typeOfProc) is "iterator" doAssert not compiles(typeof(myFoo2(), typeOfProc)) # this would give: Error: attempting to call routine: 'myFoo2' # since `typeOfProc` expects a typed expression and `myFoo2()` can # only be used in a `for` context.
Source Edit proc unsafeAddr[T](x: T): ptr T {.magic: "Addr", noSideEffect, ...raises: [], tags: [].}
-
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.
Source Edit proc unsetControlCHook() {....raises: [Exception], tags: [WriteIOEffect, RootEffect].}
- Reverts a call to setControlCHook. Source Edit
proc wasMoved[T](obj: var T) {.magic: "WasMoved", noSideEffect, ...raises: [], tags: [].}
- Resets an object obj to its initial (binary zero) value to signify it was "moved" and to signify its destructor should do nothing and ideally be optimized away. Source Edit
proc writeStackTrace() {....tags: [], gcsafe, raises: [].}
- Writes the current stack trace to stderr. This is only works for debug builds. Since it's usually used for debugging, this is proclaimed to have no IO effect! Source Edit
proc ze(x: int8): int {....deprecated, raises: [], tags: [].}
- int. This treats x as unsigned. Deprecated since version 0.19.9: Use unsigned integers instead. Source Edit zero extends a smaller integer type to
proc ze(x: int16): int {....deprecated, raises: [], tags: [].}
- int. This treats x as unsigned. Deprecated since version 0.19.9: Use unsigned integers instead. Source Edit zero extends a smaller integer type to
proc ze64(x: int): int64 {....deprecated, raises: [], tags: [].}
- int64. This treats x as unsigned. Does nothing if the size of an int is the same as int64. (This is the case on 64 bit processors.) Deprecated since version 0.19.9: Use unsigned integers instead. Source Edit zero extends a smaller integer type to
proc ze64(x: int8): int64 {....deprecated, raises: [], tags: [].}
- int64. This treats x as unsigned. Deprecated since version 0.19.9: Use unsigned integers instead. Source Edit zero extends a smaller integer type to
proc ze64(x: int16): int64 {....deprecated, raises: [], tags: [].}
- int64. This treats x as unsigned. Deprecated since version 0.19.9: Use unsigned integers instead. Source Edit zero extends a smaller integer type to
Iterators
iterator `..<`(a, b: int32): int32 {.inline, ...raises: [], tags: [].}
- A type specialized version of ..< for convenience so that mixing integer types works better. Source Edit
iterator `..<`(a, b: int64): int64 {.inline, ...raises: [], tags: [].}
- A type specialized version of ..< for convenience so that mixing integer types works better. Source Edit
iterator `..<`(a, b: uint32): uint32 {.inline, ...raises: [], tags: [].}
- A type specialized version of ..< for convenience so that mixing integer types works better. Source Edit
iterator `..<`(a, b: uint64): uint64 {.inline, ...raises: [], tags: [].}
- A type specialized version of ..< for convenience so that mixing integer types works better. Source Edit
iterator `..`(a, b: int32): int32 {.inline, ...raises: [], tags: [].}
-
A type specialized version of .. for convenience so that mixing integer types works better.
See also:
Source Edit iterator `..`(a, b: int64): int64 {.inline, ...raises: [], tags: [].}
-
A type specialized version of .. for convenience so that mixing integer types works better.
See also:
Source Edit iterator `..`(a, b: uint32): uint32 {.inline, ...raises: [], tags: [].}
-
A type specialized version of .. for convenience so that mixing integer types works better.
See also:
Source Edit iterator `..`(a, b: uint64): uint64 {.inline, ...raises: [], tags: [].}
-
A type specialized version of .. for convenience so that mixing integer types works better.
See also:
Source Edit iterator `..`[T](a, b: T): T {.inline.}
-
An alias for countup(a, b, 1).
See also:
Example:
import std/sugar let x = collect(newSeq): for i in 3 .. 7: i assert x == @[3, 4, 5, 6, 7]
Source Edit iterator countdown[T](a, b: T; step: Positive = 1): T {.inline.}
-
Counts from ordinal value a down to b (inclusive) with the given step count.
T may be any ordinal type, step may only be positive.
Note: This fails to count to low(int) if T = int for efficiency reasons.
Example:
import std/sugar let x = collect(newSeq): for i in countdown(7, 3): i assert x == @[7, 6, 5, 4, 3] let y = collect(newseq): for i in countdown(9, 2, 3): i assert y == @[9, 6, 3]
Source Edit iterator countup[T](a, b: T; step: Positive = 1): T {.inline.}
-
Counts from ordinal value a to b (inclusive) with the given step count.
T may be any ordinal type, step may only be positive.
Note: This fails to count to high(int) if T = int for efficiency reasons.
Example:
import std/sugar let x = collect(newSeq): for i in countup(3, 7): i assert x == @[3, 4, 5, 6, 7] let y = collect(newseq): for i in countup(2, 9, 3): i assert y == @[2, 5, 8]
Source Edit
Templates
template `!=`(x, y: untyped): untyped
- Unequals operator. This is a shorthand for not (x == y). Source Edit
template `&=`(x, y: typed)
-
Generic 'sink' operator for Nim.
For files an alias for write. If not specialized further, an alias for add.
Source Edit template `..<`(a, b: untyped): untyped
-
A shortcut for a .. pred(b).
for i in 5 ..< 9: echo i # => 5; 6; 7; 8
Source Edit template `..^`(a, b: untyped): untyped
- A shortcut for .. ^ to avoid the common gotcha that a space between '..' and '^' is required. Source Edit
template `=dispose`[T](x: owned(ref T))
- Source Edit
template `>%`(x, y: untyped): untyped
- Treats x and y as unsigned and compares them. Returns true if unsigned(x) > unsigned(y). Source Edit
template `>=%`(x, y: untyped): untyped
- Treats x and y as unsigned and compares them. Returns true if unsigned(x) >= unsigned(y). Source Edit
template `>=`(x, y: untyped): untyped
- "is greater or equals" operator. This is the same as y <= x. Source Edit
template `^`(x: int): BackwardsIndex
-
Builtin roof operator that can be used for convenient array access. a[^x] is a shortcut for a[a.len-x].
let a = [1, 3, 5, 7, 9] b = "abcdefgh" echo a[^1] # => 9 echo b[^2] # => g
Source Edit template `in`(x, y: untyped): untyped {.dirty.}
-
Sugar for contains.
assert(1 in (1..3) == true) assert(5 in (1..3) == false)
Source Edit template `isnot`(x, y: untyped): untyped
-
Negated version of is. Equivalent to not(x is y).
assert 42 isnot float assert @[1, 2] isnot enum
Source Edit template `notin`(x, y: untyped): untyped {.dirty.}
-
Sugar for not contains.
assert(1 notin (1..3) == false) assert(5 notin (1..3) == true)
Source Edit template alloc(size: Natural): pointer
-
Allocates a new memory block with at least size bytes.
The block has to be freed with realloc(block, 0) or dealloc(block). The block is not initialized, so reading from it before writing to it is undefined behaviour!
The allocated memory belongs to its allocating thread! Use allocShared to allocate from a shared heap.
See also:
Source Edit template alloc0(size: Natural): pointer
-
Allocates a new memory block with at least size bytes.
The block has to be freed with realloc(block, 0) or dealloc(block). The block is initialized with all bytes containing zero, so it is somewhat safer than alloc.
The allocated memory belongs to its allocating thread! Use allocShared0 to allocate from a shared heap.
Source Edit template closureScope(body: untyped): untyped
-
Useful when creating a closure in a loop to capture local loop variables by their current iteration values.
Note: This template may not work in some cases, use capture instead.
Example:
var myClosure : proc() # without closureScope: for i in 0 .. 5: let j = i if j == 3: myClosure = proc() = echo j myClosure() # outputs 5. `j` is changed after closure creation # with closureScope: for i in 0 .. 5: closureScope: # Everything in this scope is locked after closure creation let j = i if j == 3: myClosure = proc() = echo j myClosure() # outputs 3
Source Edit template currentSourcePath(): string
-
Returns the full file-system path of the current source.
To get the directory containing the current source, use it with os.parentDir() as currentSourcePath.parentDir().
The path returned by this template is set at compile time.
See the docstring of macros.getProjectPath() for an example to see the distinction between the currentSourcePath and getProjectPath.
See also:
Source Edit template disarm(x: typed)
- Useful for disarming dangling pointers explicitly for --newruntime. Regardless of whether --newruntime is used or not this sets the pointer or callback x to nil. This is an experimental API! Source Edit
template dumpAllocstats(code: untyped)
- Source Edit
template excl[T](x: var set[T]; y: set[T])
-
Excludes the set y from the set x.
Example:
var a = {1, 3, 5, 7} var b = {3, 4, 5} a.excl(b) assert a == {1, 7}
Source Edit template formatErrorIndexBound[T](i, a, b: T): string
- Source Edit
template formatErrorIndexBound[T](i, n: T): string
- Source Edit
template incl[T](x: var set[T]; y: set[T])
-
Includes the set y in the set x.
Example:
var a = {1, 3, 5, 7} var b = {4, 5, 6} a.incl(b) assert a == {1, 3, 4, 5, 6, 7}
Source Edit template likely(val: bool): bool
-
Hints the optimizer that val is likely going to be true.
You can use this template to decorate a branch condition. On certain platforms this can help the processor predict better which branch is going to be run. Example:
for value in inputValues: if likely(value <= 100): process(value) else: echo "Value too big!"
On backends without branch prediction (JS and the nimscript VM), this template will not affect code execution.
Source Edit template new[T: ref](a: var T)
- Creates a new object of T's underlying object type and returns a safe (traced) reference to it in a. Source Edit
template newException(exceptn: typedesc; message: string; parentException: ref Exception = nil): untyped
- Creates an exception object of type exceptn, initializes it's name and sets its msg field to message. Returns the new exception object. Source Edit
template once(body: untyped): untyped
-
Executes a block of code only once (the first time the block is reached).
proc draw(t: Triangle) = once: graphicsInit() line(t.p1, t.p2) line(t.p2, t.p3) line(t.p3, t.p1)
Source Edit template rangeCheck(cond)
- Helper for performing user-defined range checks. Such checks will be performed only when the rangechecks compile-time option is enabled. Source Edit
template realloc(p: pointer; newSize: Natural): pointer
-
Grows or shrinks a given memory block.
If p is nil then a new memory block is returned. In either way the block has at least newSize bytes. If newSize == 0 and p is not nil realloc calls dealloc(p). In other cases the block has to be freed with dealloc(block).
The allocated memory belongs to its allocating thread! Use reallocShared to reallocate from a shared heap.
Source Edit template realloc0(p: pointer; oldSize, newSize: Natural): pointer
-
Grows or shrinks a given memory block.
If p is nil then a new memory block is returned. In either way the block has at least newSize bytes. If newSize == 0 and p is not nil realloc calls dealloc(p). In other cases the block has to be freed with dealloc(block).
The block is initialized with all bytes containing zero, so it is somewhat safer then realloc
The allocated memory belongs to its allocating thread! Use reallocShared to reallocate from a shared heap.
Source Edit template setupForeignThreadGc()
- With --gc:arc a nop. Source Edit
template tearDownForeignThreadGc()
- With --gc:arc a nop. Source Edit
template unlikely(val: bool): bool
-
Hints the optimizer that val is likely going to be false.
You can use this proc to decorate a branch condition. On certain platforms this can help the processor predict better which branch is going to be run. Example:
for value in inputValues: if unlikely(value > 100): echo "Value too big!" else: process(value)
On backends without branch prediction (JS and the nimscript VM), this template will not affect code execution.
Source Edit template unsafeNew[T: ref](a: var T; size: Natural)
-
Creates a new object of T's underlying object type 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!
Source Edit
Exports
-
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, $, $, $, $, $, $, $, $, $, $, $, $, addInt, addInt, addInt, repr, repr, repr, repr, repr, repr, repr, repr, repr, repr, repr, repr, repr, repr, reprDiscriminant, repr, repr, repr, repr, repr, repr, len, $, $, []=, newWideCString, toWideCString, WideCString, $, newWideCString, newWideCString, WideCStringObj, Utf16Char, newWideCString, $, [], writeFile, write, File, write, writeChars, endOfFile, getFilePos, readChars, readLines, write, readLine, open, writeFile, reopen, readChar, writeBuffer, stdmsg, getFileHandle, close, write, getOsFileHandle, readFile, setFilePos, write, setStdIoUnbuffered, readChars, lines, stdout, readLines, getFileSize, FileHandle, write, write, readBytes, writeLine, write, setInheritable, readLine, open, flushFile, readAll, FileMode, write, readBuffer, stderr, stdin, open, writeBytes, lines