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.
Module system
Types
int
- default integer type; bitwidth depends on architecture, but is always the same as a pointer Source
int8
- signed 8 bit integer type Source
int16
- signed 16 bit integer type Source
int32
- signed 32 bit integer type Source
int64
- signed 64 bit integer type Source
uint
- unsigned default integer type Source
uint8
- unsigned 8 bit integer type Source
uint16
- unsigned 16 bit integer type Source
uint32
- unsigned 32 bit integer type Source
uint64
- unsigned 64 bit integer type Source
float
- default floating point type Source
float32
- 32 bit floating point type Source
float64
- 64 bit floating point type Source
bool = enum false = 0, true = 1
- built-in boolean type Source
char
- built-in 8 bit character type (unsigned) Source
string
- built-in string type Source
cstring
- built-in cstring (compatible string) type Source
pointer
- built-in pointer type, use the addr operator to get a pointer to a variable Source
Ordinal[T]
- Generic ordinal type. Includes integer, bool, character, and enumeration types as well as their subtypes. Note uint and uint64 are not ordinal types for implementation reasons Source
ptr[T]
- built-in generic untraced pointer type Source
ref[T]
- built-in generic traced pointer type Source
expr
- meta type to denote an expression (for templates) Source
stmt
- meta type to denote a statement (for templates) Source
typedesc
- meta type to denote a type description Source
void
- meta type to denote the absence of any type Source
auto
- meta type for automatic type determination Source
any = distinct auto
- meta type for any supported type Source
untyped
- meta type to denote an expression that is not resolved (for templates) Source
typed
- meta type to denote an expression that is resolved (for templates) Source
SomeSignedInt = int | int8 | int16 | int32 | int64
- type class matching all signed integer types Source
SomeUnsignedInt = uint | uint8 | uint16 | uint32 | uint64
- type class matching all unsigned integer types Source
SomeInteger = SomeSignedInt | SomeUnsignedInt
- type class matching all integer types Source
SomeOrdinal = int | int8 | int16 | int32 | int64 | bool | enum | uint8 | uint16 | uint32
- type class matching all ordinal types; however this includes enums with holes. Source
SomeReal = float | float32 | float64
- type class matching all floating point number types Source
SomeNumber = SomeInteger | SomeReal
- type class matching all number types Source
range[T]
- Generic type to construct range types. Source
array[I, T]
- Generic type to construct fixed-length arrays. Source
openArray[T]
- Generic type to construct open arrays. Open arrays are implemented as a pointer to the array data and a length field. Source
varargs[T]
- Generic type to construct a varargs type. Source
seq[T]
- Generic type to construct sequences. Source
set[T]
- Generic type to construct bit sets. Source
Slice[T] = object a*, b*: T ## the bounds
- builtin slice type Source
- Source
guarded
- Source
byte = uint8
- this is an alias for uint8, that is an unsigned int 8 bits wide. Source
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
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
RootObj = 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 allowed. Source
RootRef = ref RootObj
- reference to RootObj Source
RootEffect = object of RootObj
- base effect class; each effect should inherit from TEffect unless you know what you doing. Source
TimeEffect = object of RootEffect
- Time effect. Source
IOEffect = object of RootEffect
- IO effect. Source
ReadIOEffect = object of IOEffect
- Effect describing a read IO operation. Source
WriteIOEffect = object of IOEffect
- Effect describing a write IO operation. Source
ExecIOEffect = object of IOEffect
- Effect describing an executing IO operation. Source
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. trace: string
-
Base exception class.
Each exception has to inherit from Exception. See the full exception hierarchy.
Source SystemError = object of Exception
-
Abstract class for exceptions that the runtime system raises.
See the full exception hierarchy.
Source IOError = object of SystemError
-
Raised if an IO error occurred.
See the full exception hierarchy.
Source OSError = object of SystemError errorCode*: int32 ## OS-defined error code describing this error.
-
Raised if an operating system service failed.
See the full exception hierarchy.
Source LibraryError = object of OSError
-
Raised if a dynamic library could not be loaded.
See the full exception hierarchy.
Source ResourceExhaustedError = object of SystemError
-
Raised if a resource request could not be fulfilled.
See the full exception hierarchy.
Source ArithmeticError = object of Exception
-
Raised if any kind of arithmetic error occurred.
See the full exception hierarchy.
Source DivByZeroError = object of ArithmeticError
-
Raised for runtime integer divide-by-zero errors.
See the full exception hierarchy.
Source OverflowError = object of ArithmeticError
-
Raised for runtime integer overflows.
This happens for calculations whose results are too large to fit in the provided bits. See the full exception hierarchy.
Source AccessViolationError = object of Exception
-
Raised for invalid memory access errors
See the full exception hierarchy.
Source AssertionError = object of Exception
-
Raised when assertion is proved wrong.
Usually the result of using the assert() template. See the full exception hierarchy.
Source ValueError = object of Exception
- Raised for string and object conversion errors. Source
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. See the full exception hierarchy.
Source OutOfMemError = object of SystemError
-
Raised for unsuccessful attempts to allocate memory.
See the full exception hierarchy.
Source IndexError = object of Exception
-
Raised if an array index is out of bounds.
See the full exception hierarchy.
Source FieldError = object of Exception
-
Raised if a record field is not accessible because its dicriminant's value does not fit.
See the full exception hierarchy.
Source RangeError = object of Exception
-
Raised if a range check error occurred.
See the full exception hierarchy.
Source StackOverflowError = object of SystemError
-
Raised if the hardware stack used for subroutine calls overflowed.
See the full exception hierarchy.
Source ReraiseError = object of Exception
-
Raised if there is no exception to reraise.
See the full exception hierarchy.
Source ObjectAssignmentError = object of Exception
-
Raised if an object gets assigned to its parent's object.
See the full exception hierarchy.
Source ObjectConversionError = object of Exception
-
Raised if an object is converted to an incompatible object type. You can use of operator to check if conversion will succeed.
See the full exception hierarchy.
Source FloatingPointError = object of Exception
-
Base class for floating point exceptions.
See the full exception hierarchy.
Source FloatInvalidOpError = object of FloatingPointError
-
Raised by invalid operations according to IEEE.
Raised by 0.0/0.0, for example. See the full exception hierarchy.
Source FloatDivByZeroError = object of FloatingPointError
-
Raised by division by zero.
Divisor is zero and dividend is a finite nonzero number. See the full exception hierarchy.
Source FloatOverflowError = object of FloatingPointError
-
Raised for overflows.
The operation produced a result that exceeds the range of the exponent. See the full exception hierarchy.
Source FloatUnderflowError = object of FloatingPointError
-
Raised for underflows.
The operation produced a result that is too small to be represented as a normal number. See the full exception hierarchy.
Source FloatInexactError = object of FloatingPointError
-
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! See the full exception hierarchy.
Source DeadThreadError = object of Exception
-
Raised if it is attempted to send a message to a dead thread.
See the full exception hierarchy.
Source TResult = enum Failure, Success
- Source
Endianness = enum littleEndian, bigEndian
- is a type describing the endianness of a processor. Source
TaintedString = string
- a distinct string type that is tainted. It is an alias for string if the taint mode is not turned on. Use the -d:taintMode command line switch to turn the taint mode on. Source
LibHandle = pointer
- Source
ProcAddr = pointer
- Source
ByteAddress = int
- is the signed integer type that should be used for converting pointers to integer addresses for readability. Source
BiggestInt = int64
- is an alias for the biggest signed integer type the Nim compiler supports. Currently this is int64, but it is platform-dependant in general. Source
BiggestFloat = float64
- is an alias for the biggest floating point type the Nim compiler supports. Currently this is float64, but it is platform-dependant in general. Source
clong = int
- This is the same as the type long in C. Source
culong = uint
- This is the same as the type unsigned long in C. Source
cchar = char
- This is the same as the type char in C. Source
cschar = int8
- This is the same as the type signed char in C. Source
cshort = int16
- This is the same as the type short in C. Source
cint = int32
- This is the same as the type int in C. Source
csize = int
- This is the same as the type size_t in C. Source
clonglong = int64
- This is the same as the type long long in C. Source
cfloat = float32
- This is the same as the type float in C. Source
cdouble = float64
- This is the same as the type double in C. Source
clongdouble = BiggestFloat
- This is the same as the type long double in C. This C type is not supported by Nim's code generator Source
cuchar = char
- This is the same as the type unsigned char in C. Source
cushort = uint16
- This is the same as the type unsigned short in C. Source
cuint = uint32
- This is the same as the type unsigned int in C. Source
culonglong = uint64
- This is the same as the type unsigned long long in C. Source
cstringArray = ptr array[0 .. ArrayDummySize, 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 to convert it into a seq[string]. Source
PFloat32 = ptr float32
- an alias for ptr float32 Source
PFloat64 = ptr float64
- an alias for ptr float64 Source
PInt64 = ptr int64
- an alias for ptr int64 Source
PInt32 = ptr int32
- an alias for ptr int32 Source
GC_Strategy = enum gcThroughput, ## optimize for throughput gcResponsiveness, ## optimize for responsiveness (default) gcOptimizeTime, ## optimize for speed gcOptimizeSpace ## optimize for memory footprint
- the strategy the GC should use for the application Source
PFrame = ptr TFrame
- represents a runtime frame of the call stack; part of the debugger API. Source
TFrame = 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
- the frame itself Source
File = ptr CFile
- The type representing a file handle. Source
FileMode = enum fmRead, ## Open the file for read access only. fmWrite, ## Open the file for write access only. fmReadWrite, ## Open the file for read and write access. ## If the file does not exist, it will be ## created. fmReadWriteExisting, ## Open the file for read and write access. ## If the file does not exist, it will not be ## created. fmAppend ## Open the file for writing only; append data ## at the end.
- The file mode when opening a file. Source
FileHandle = cint
- type that represents an OS file handle; this is useful for low-level file access Source
AlignType = BiggestFloat
- Source
RefCount = int
- Source
Utf16Char = distinct int16
- Source
WideCString = ref array[0 .. 1000000, Utf16Char]
- Source
NimNode = ref NimNodeObj
- represents a Nim AST node. Macros operate on this type. Source
Vars
programResult: int
- modify this variable to specify the exit code of the program under normal circumstances. When the program is terminated prematurely using quit, this value is ignored. Source
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. 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
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. 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
outOfMemHook: proc () {.nimcall, tags: [], gcsafe, locks: 0.}
-
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 stdin: File
- The standard input stream. Source
stdout: File
- The standard output stream. Source
stderr: File
- The standard error stream. Source
errorMessageWriter: (proc (msg: string) {.tags: [WriteIOEffect], gcsafe, locks: 0.})
- Function that will be called instead of stdmsg.write when printing stacktrace. Unstable API. Source
Lets
nimvm: bool = false
- may be used only in "when" expression. It is true in Nim VM context and false otherwise Source
Consts
on = true
- alias for true Source
off = false
- alias for false Source
appType: string = ""
- a string that describes the application type. Possible values: "console", "gui", "lib". Source
NoFakeVars = false
- true if the backend doesn't support "fake variables" like 'var EBADF {.importc.}: cint'. Source
isMainModule: bool = false
- is 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
CompileDate: string = "0000-00-00"
- is the date of compilation as a string of the form YYYY-MM-DD. This works thanks to compiler magic. Source
CompileTime: string = "00:00:00"
- is the time of compilation as a string of the form HH:MM:SS. This works thanks to compiler magic. Source
cpuEndian: Endianness = littleEndian
- is 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
hostOS: string = ""
- a string that describes the host operating system. Possible values: "windows", "macosx", "linux", "netbsd", "freebsd", "openbsd", "solaris", "aix", "standalone". Source
hostCPU: string = ""
- a string that describes the host CPU. Possible values: "i386", "alpha", "powerpc", "powerpc64", "powerpc64el", "sparc", "amd64", "mips", "mipsel", "arm", "arm64". Source
QuitSuccess = 0
- is the value that should be passed to quit to indicate success. Source
QuitFailure = 1
- is the value that should be passed to quit to indicate failure. Source
Inf = inf
- contains the IEEE floating point value of positive infinity. Source
NegInf = -inf
- contains the IEEE floating point value of negative infinity. Source
NaN = nan
- 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 classify procedure in the module math for checking for NaN. Source
NimMajor: int = 0
- is the major number of Nim's version. Source
NimMinor: int = 13
- is the minor number of Nim's version. Source
NimPatch: int = 0
- is the patch number of Nim's version. Source
NimVersion: string = "0.13.0"
- is the version of Nim as a string. Source
nativeStackTraceSupported = false
- Source
Procs
proc defined(x: expr): bool {.magic: "Defined", noSideEffect, compileTime.}
-
Special compile-time procedure that checks whether x is defined. x is an external symbol introduced through the compiler's -d:x switch to enable build time conditionals:
when not defined(release): # Do here programmer friendly expensive sanity checks. # Put here the normal code
Source proc declared(x: expr): bool {.magic: "Defined", noSideEffect, compileTime.}
-
Special compile-time procedure that checks whether x is declared. x has to be an identifier or a qualified identifier. This can be used to check whether a library provides a certain feature or not:
when not declared(strutils.toUpper): # provide our own toUpper proc here, because strutils is # missing it.
Source proc definedInScope(x: expr): bool {.magic: "DefinedInScope", noSideEffect, deprecated, compileTime.}
- Deprecated since version 0.9.6: Use declaredInScope instead. Source
proc declaredInScope(x: expr): bool {.magic: "DefinedInScope", noSideEffect, compileTime.}
- Special compile-time procedure that checks whether x is declared in the current scope. x has to be an identifier. Source
proc `addr`[T](x: var T): ptr T {.magic: "Addr", noSideEffect.}
-
Builtin 'addr' operator for taking the address of a memory location. Cannot be overloaded.
var buf: seq[char] = @['a','b','c'] p: pointer = buf[1].addr echo cast[ptr char](p)[] # b
Source proc unsafeAddr[T](x: var T): ptr T {.magic: "Addr", noSideEffect.}
- Builtin 'addr' operator for taking the address of a memory location. This works even for let variables or parameters for better interop with C and so it is considered even more unsafe than the ordinary addr. Cannot be overloaded. Source
proc `type`[](x: expr): typedesc {.magic: "TypeOf", noSideEffect, compileTime.}
- Builtin 'type' operator for accessing the type of an expression. Cannot be overloaded. Source
proc `not`(x: bool): bool {.magic: "Not", noSideEffect.}
- Boolean not; returns true iff x == false. Source
proc `and`(x, y: bool): bool {.magic: "And", noSideEffect.}
- Boolean and; returns true iff x == y == true. Evaluation is lazy: if x is false, y will not even be evaluated. Source
proc `or`(x, y: bool): bool {.magic: "Or", noSideEffect.}
- Boolean or; returns true iff not (not x and not y). Evaluation is lazy: if x is true, y will not even be evaluated. Source
proc `xor`(x, y: bool): bool {.magic: "Xor", noSideEffect.}
- Boolean exclusive or; returns true iff x != y. Source
proc new[T](a: var ref T) {.magic: "New", noSideEffect.}
- creates a new object of type T and returns a safe (traced) reference to it in a. Source
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 proc internalNew[T](a: var ref T) {.magic: "New", noSideEffect.}
- leaked implementation detail. Do not use. Source
proc new[T](a: var ref T; finalizer: proc (x: ref T) {.nimcall.}) {.magic: "NewFinalize", noSideEffect.}
- creates a new object of type T and returns a safe (traced) reference to it in a. When the garbage collector frees the object, finalizer is called. The finalizer may not keep a reference to the object pointed to by x. The finalizer cannot prevent the GC from freeing the object. Note: The finalizer refers to the type T, not to the object! This means that for each object of type T the finalizer will be called! Source
proc reset[T](obj: var T) {.magic: "Reset", noSideEffect.}
- resets an object obj to its initial (binary zero) value. This needs to be called before any possible object branch transition. Source
proc high[T](x: T): T {.magic: "High", noSideEffect.}
-
returns the highest possible index of an array, a sequence, a string or the highest possible value of an ordinal value x. As a special semantic rule, x may also be a type identifier. high(int) is Nim's way of writing INT_MAX or MAX_INT.
var arr = [1,2,3,4,5,6,7] high(arr) #=> 6 high(2) #=> 9223372036854775807
Source proc low[T](x: T): T {.magic: "Low", noSideEffect.}
-
returns the lowest possible index of an array, a sequence, a string or the lowest possible value of an ordinal value x. As a special semantic rule, x may also be a type identifier.
var arr = [1,2,3,4,5,6,7] low(arr) #=> 0 low(2) #=> -9223372036854775808
Source proc `[]`[I, T](a: T; i: I): T {.noSideEffect, magic: "ArrGet".}
- Source
proc `[]=`[I, T, S](a: T; i: I; x: S) {.noSideEffect, magic: "ArrPut".}
- Source
proc `=`[T](dest: var T; src: T) {.noSideEffect, magic: "Asgn".}
- Source
proc `..`[T](a, b: T): Slice[T] {.noSideEffect, inline, magic: "DotDot".}
- 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. Source
proc `..`[T](b: T): Slice[T] {.noSideEffect, inline, magic: "DotDot".}
- slice operator that constructs an interval [default(T), b] Source
proc `==`[Enum](x, y: Enum): bool {.magic: "EqEnum", noSideEffect.}
-
Checks whether values within the same enum have the same underlying value
type Enum1 = enum Field1 = 3, Field2 Enum2 = enum Place1, Place2 = 3 var e1 = Field1 e2 = Enum1(Place2) echo (e1 == e2) # true echo (e1 == Place2) # raises error
Source proc `==`(x, y: pointer): bool {.magic: "EqRef", noSideEffect.}
-
var # this is a wildly dangerous example a = cast[pointer](0) b = cast[pointer](nil) echo (a == b) # true due to the special meaning of `nil`/0 as a pointer
Source proc `==`(x, y: string): bool {.magic: "EqStr", noSideEffect.}
- Checks for equality between two string variables Source
proc `==`(x, y: cstring): bool {.magic: "EqCString", noSideEffect.}
- Checks for equality between two cstring variables Source
proc `==`(x, y: char): bool {.magic: "EqCh", noSideEffect.}
- Checks for equality between two char variables Source
proc `==`(x, y: bool): bool {.magic: "EqB", noSideEffect.}
- Checks for equality between two bool variables Source
proc `==`[T](x, y: set[T]): bool {.magic: "EqSet", noSideEffect.}
-
Checks for equality between two variables of type set
var a = {1, 2, 2, 3} # duplication in sets is ignored var b = {1, 2, 3} echo (a == b) # true
Source proc `==`[T](x, y: ref T): bool {.magic: "EqRef", noSideEffect.}
- Checks that two ref variables refer to the same item Source
proc `==`[T](x, y: ptr T): bool {.magic: "EqRef", noSideEffect.}
- Checks that two ptr variables refer to the same item Source
proc `==`[T](x, y: T): bool {.magic: "EqProc", noSideEffect.}
- Checks that two proc variables refer to the same procedure Source
proc `<=`[Enum](x, y: Enum): bool {.magic: "LeEnum", noSideEffect.}
- Source
proc `<=`(x, y: string): bool {.magic: "LeStr", noSideEffect.}
- Source
proc `<=`(x, y: char): bool {.magic: "LeCh", noSideEffect.}
- Source
proc `<=`[T](x, y: set[T]): bool {.magic: "LeSet", noSideEffect.}
- Source
proc `<=`(x, y: bool): bool {.magic: "LeB", noSideEffect.}
- Source
proc `<=`[T](x, y: ref T): bool {.magic: "LePtr", noSideEffect.}
- Source
proc `<=`(x, y: pointer): bool {.magic: "LePtr", noSideEffect.}
- Source
proc `<`[Enum](x, y: Enum): bool {.magic: "LtEnum", noSideEffect.}
- Source
proc `<`(x, y: string): bool {.magic: "LtStr", noSideEffect.}
- Source
proc `<`(x, y: char): bool {.magic: "LtCh", noSideEffect.}
- Source
proc `<`[T](x, y: set[T]): bool {.magic: "LtSet", noSideEffect.}
- Source
proc `<`(x, y: bool): bool {.magic: "LtB", noSideEffect.}
- Source
proc `<`[T](x, y: ref T): bool {.magic: "LtPtr", noSideEffect.}
- Source
proc `<`[T](x, y: ptr T): bool {.magic: "LtPtr", noSideEffect.}
- Source
proc `<`(x, y: pointer): bool {.magic: "LtPtr", noSideEffect.}
- Source
proc unsafeNew[T](a: var ref T; size: Natural) {.magic: "New", noSideEffect.}
- creates a new object of type T and returns a safe (traced) reference to it in a. This is unsafe as it allocates an object of the passed size. This should only be used for optimization purposes when you know what you're doing! Source
proc sizeof[T](x: T): int {.magic: "SizeOf", noSideEffect.}
-
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).
sizeof('A') #=> 1 sizeof(2) #=> 8
Source proc sizeof[](x: typedesc): int {.magic: "SizeOf", noSideEffect.}
- Source
proc `<`[T](x: Ordinal[T]): T {.magic: "UnaryLt", noSideEffect.}
-
unary < that can be used for nice looking excluding ranges:
for i in 0 .. <10: echo i
Semantically this is the same as pred.
Source proc succ[T](x: Ordinal[T]; y = 1): T {.magic: "Succ", noSideEffect.}
- returns the y-th successor of the value x. T has to be an ordinal type. If such a value does not exist, EOutOfRange is raised or a compile time error occurs. Source
proc pred[T](x: Ordinal[T]; y = 1): T {.magic: "Pred", noSideEffect.}
- returns the y-th predecessor of the value x. T has to be an ordinal type. If such a value does not exist, EOutOfRange is raised or a compile time error occurs. Source
proc inc[T](x: var T; y = 1) {.magic: "Inc", noSideEffect.}
-
increments the ordinal x by y. If such a value does not exist, EOutOfRange is raised or a compile time error occurs. This is a short notation for: x = succ(x, y).
var i = 2 inc(i) #=> 3 inc(i, 3) #=> 6
Source proc dec[T](x: var T; y = 1) {.magic: "Dec", noSideEffect.}
-
decrements the ordinal x by y. If such a value does not exist, EOutOfRange is raised or a compile time error occurs. This is a short notation for: x = pred(x, y).
var i = 2 dec(i) #=> 1 dec(i, 3) #=> -2
Source proc newSeq[T](s: var seq[T]; len: Natural) {.magic: "NewSeq", noSideEffect.}
-
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, which can be a problem for sequences containing strings since their value will be nil. 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) inputStrings[0] = "The fourth" inputStrings[1] = "assignment" inputStrings[2] = "would crash" #inputStrings[3] = "out of bounds"
Source 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, which can be a problem for sequences containing strings since their value will be nil. After the creation of the sequence you should assign entries to the sequence instead of adding them. Example:
var inputStrings = newSeq[string](3) inputStrings[0] = "The fourth" inputStrings[1] = "assignment" inputStrings[2] = "would crash" #inputStrings[3] = "out of bounds"
Source proc len[TOpenArray](x: TOpenArray): int {.magic: "LengthOpenArray", noSideEffect.}
- Source
proc len(x: string): int {.magic: "LengthStr", noSideEffect.}
- Source
proc len(x: cstring): int {.magic: "LengthStr", noSideEffect.}
- Source
proc len[I, T](x: array[I, T]): int {.magic: "LengthArray", noSideEffect.}
- Source
proc len[T](x: seq[T]): int {.magic: "LengthSeq", noSideEffect.}
-
returns the length of an array, an openarray, a sequence or a string. This is roughly the same as high(T)-low(T)+1, but its resulting type is always an int.
var arr = [1,1,1,1,1] len(arr) #=> 5 for i in 0..<arr.len: echo arr[i] #=> 1,1,1,1,1
Source proc incl[T](x: var set[T]; y: T) {.magic: "Incl", noSideEffect.}
-
includes element y to the set x. This is the same as x = x + {y}, but it might be more efficient.
var a = initSet[int](4) a.incl(2) #=> {2} a.incl(3) #=> {2, 3}
Source proc excl[T](x: var set[T]; y: T) {.magic: "Excl", noSideEffect.}
-
excludes element y to the set x. This is the same as x = x - {y}, but it might be more efficient.
var b = {2,3,5,6,12,545} b.excl(5) #=> {2,3,6,12,545}
Source proc card[T](x: set[T]): int {.magic: "Card", noSideEffect.}
-
returns the cardinality of the set x, i.e. the number of elements in the set.
var i = {1,2,3,4} card(i) #=> 4
Source proc ord[T](x: T): int {.magic: "Ord", noSideEffect.}
-
returns the internal int value of an ordinal value x.
ord('A') #=> 65
Source proc chr(u: range[0 .. 255]): char {.magic: "Chr", noSideEffect.}
-
converts an int in the range 0..255 to a character.
chr(65) #=> A
Source proc ze(x: int8): int {.magic: "Ze8ToI", noSideEffect.}
- zero extends a smaller integer type to int. This treats x as unsigned. Source
proc ze(x: int16): int {.magic: "Ze16ToI", noSideEffect.}
- zero extends a smaller integer type to int. This treats x as unsigned. Source
proc ze64(x: int8): int64 {.magic: "Ze8ToI64", noSideEffect.}
- zero extends a smaller integer type to int64. This treats x as unsigned. Source
proc ze64(x: int16): int64 {.magic: "Ze16ToI64", noSideEffect.}
- zero extends a smaller integer type to int64. This treats x as unsigned. Source
proc ze64(x: int32): int64 {.magic: "Ze32ToI64", noSideEffect.}
- zero extends a smaller integer type to int64. This treats x as unsigned. Source
proc ze64(x: int): int64 {.magic: "ZeIToI64", noSideEffect.}
- zero extends a smaller integer type to 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.) Source
proc toU8(x: int): int8 {.magic: "ToU8", noSideEffect.}
- treats x as unsigned and converts it to a byte by taking the last 8 bits from x. Source
proc toU16(x: int): int16 {.magic: "ToU16", noSideEffect.}
- treats x as unsigned and converts it to an int16 by taking the last 16 bits from x. Source
proc toU32(x: int64): int32 {.magic: "ToU32", noSideEffect.}
- treats x as unsigned and converts it to an int32 by taking the last 32 bits from x. Source
proc `+`(x: int): int {.magic: "UnaryPlusI", noSideEffect.}
- Source
proc `+`(x: int8): int8 {.magic: "UnaryPlusI", noSideEffect.}
- Source
proc `+`(x: int16): int16 {.magic: "UnaryPlusI", noSideEffect.}
- Source
proc `+`(x: int32): int32 {.magic: "UnaryPlusI", noSideEffect.}
- Source
proc `+`(x: int64): int64 {.magic: "UnaryPlusI", noSideEffect.}
- Unary + operator for an integer. Has no effect. Source
proc `-`(x: int): int {.magic: "UnaryMinusI", noSideEffect.}
- Source
proc `-`(x: int8): int8 {.magic: "UnaryMinusI", noSideEffect.}
- Source
proc `-`(x: int16): int16 {.magic: "UnaryMinusI", noSideEffect.}
- Source
proc `-`(x: int32): int32 {.magic: "UnaryMinusI", noSideEffect.}
- Source
proc `-`(x: int64): int64 {.magic: "UnaryMinusI64", noSideEffect.}
- Unary - operator for an integer. Negates x. Source
proc `not`(x: int): int {.magic: "BitnotI", noSideEffect.}
- Source
proc `not`(x: int8): int8 {.magic: "BitnotI", noSideEffect.}
- Source
proc `not`(x: int16): int16 {.magic: "BitnotI", noSideEffect.}
- Source
proc `not`(x: int32): int32 {.magic: "BitnotI", noSideEffect.}
- computes the bitwise complement of the integer x. Source
proc `not`(x: int64): int64 {.magic: "BitnotI", noSideEffect.}
- Source
proc `+`(x, y: int): int {.magic: "AddI", noSideEffect.}
- Source
proc `+`(x, y: int8): int8 {.magic: "AddI", noSideEffect.}
- Source
proc `+`(x, y: int16): int16 {.magic: "AddI", noSideEffect.}
- Source
proc `+`(x, y: int32): int32 {.magic: "AddI", noSideEffect.}
- Binary + operator for an integer. Source
proc `+`(x, y: int64): int64 {.magic: "AddI", noSideEffect.}
- Source
proc `-`(x, y: int): int {.magic: "SubI", noSideEffect.}
- Source
proc `-`(x, y: int8): int8 {.magic: "SubI", noSideEffect.}
- Source
proc `-`(x, y: int16): int16 {.magic: "SubI", noSideEffect.}
- Source
proc `-`(x, y: int32): int32 {.magic: "SubI", noSideEffect.}
- Binary - operator for an integer. Source
proc `-`(x, y: int64): int64 {.magic: "SubI", noSideEffect.}
- Source
proc `*`(x, y: int): int {.magic: "MulI", noSideEffect.}
- Source
proc `*`(x, y: int8): int8 {.magic: "MulI", noSideEffect.}
- Source
proc `*`(x, y: int16): int16 {.magic: "MulI", noSideEffect.}
- Source
proc `*`(x, y: int32): int32 {.magic: "MulI", noSideEffect.}
- Binary * operator for an integer. Source
proc `*`(x, y: int64): int64 {.magic: "MulI", noSideEffect.}
- Source
proc `div`(x, y: int): int {.magic: "DivI", noSideEffect.}
- Source
proc `div`(x, y: int8): int8 {.magic: "DivI", noSideEffect.}
- Source
proc `div`(x, y: int16): int16 {.magic: "DivI", noSideEffect.}
- Source
proc `div`(x, y: int32): int32 {.magic: "DivI", noSideEffect.}
-
computes the integer division. This is roughly the same as floor(x/y).
1 div 2 == 0 2 div 2 == 1 3 div 2 == 1 7 div 5 == 1
Source proc `div`(x, y: int64): int64 {.magic: "DivI", noSideEffect.}
- Source
proc `mod`(x, y: int): int {.magic: "ModI", noSideEffect.}
- Source
proc `mod`(x, y: int8): int8 {.magic: "ModI", noSideEffect.}
- Source
proc `mod`(x, y: int16): int16 {.magic: "ModI", noSideEffect.}
- Source
proc `mod`(x, y: int32): int32 {.magic: "ModI", noSideEffect.}
-
computes the integer modulo operation (remainder). This is the same as x - (x div y) * y.
(7 mod 5) == 2
Source proc `mod`(x, y: int64): int64 {.magic: "ModI", noSideEffect.}
- Source
proc `shr`(x, y: int): int {.magic: "ShrI", noSideEffect.}
- Source
proc `shr`(x, y: int8): int8 {.magic: "ShrI", noSideEffect.}
- Source
proc `shr`(x, y: int16): int16 {.magic: "ShrI", noSideEffect.}
- Source
proc `shr`(x, y: int32): int32 {.magic: "ShrI", noSideEffect.}
- Source
proc `shr`(x, y: int64): int64 {.magic: "ShrI", noSideEffect.}
- computes the shift right operation of x and y, filling vacant bit positions with zeros. Source
proc `shl`(x, y: int): int {.magic: "ShlI", noSideEffect.}
- Source
proc `shl`(x, y: int8): int8 {.magic: "ShlI", noSideEffect.}
- Source
proc `shl`(x, y: int16): int16 {.magic: "ShlI", noSideEffect.}
- Source
proc `shl`(x, y: int32): int32 {.magic: "ShlI", noSideEffect.}
- Source
proc `shl`(x, y: int64): int64 {.magic: "ShlI", noSideEffect.}
-
computes the shift left operation of x and y.
1'i32 shl 4 == 0x0000_0010 1'i64 shl 4 == 0x0000_0000_0000_0010
Source proc `and`(x, y: int): int {.magic: "BitandI", noSideEffect.}
- Source
proc `and`(x, y: int8): int8 {.magic: "BitandI", noSideEffect.}
- Source
proc `and`(x, y: int16): int16 {.magic: "BitandI", noSideEffect.}
- Source
proc `and`(x, y: int32): int32 {.magic: "BitandI", noSideEffect.}
- Source
proc `and`(x, y: int64): int64 {.magic: "BitandI", noSideEffect.}
-
computes the bitwise and of numbers x and y.
(0xffff'i16 and 0x0010'i16) == 0x0010
Source proc `or`(x, y: int): int {.magic: "BitorI", noSideEffect.}
- Source
proc `or`(x, y: int8): int8 {.magic: "BitorI", noSideEffect.}
- Source
proc `or`(x, y: int16): int16 {.magic: "BitorI", noSideEffect.}
- Source
proc `or`(x, y: int32): int32 {.magic: "BitorI", noSideEffect.}
- Source
proc `or`(x, y: int64): int64 {.magic: "BitorI", noSideEffect.}
-
computes the bitwise or of numbers x and y.
(0x0005'i16 or 0x0010'i16) == 0x0015
Source proc `xor`(x, y: int): int {.magic: "BitxorI", noSideEffect.}
- Source
proc `xor`(x, y: int8): int8 {.magic: "BitxorI", noSideEffect.}
- Source
proc `xor`(x, y: int16): int16 {.magic: "BitxorI", noSideEffect.}
- Source
proc `xor`(x, y: int32): int32 {.magic: "BitxorI", noSideEffect.}
- Source
proc `xor`(x, y: int64): int64 {.magic: "BitxorI", noSideEffect.}
-
computes the bitwise xor of numbers x and y.
(0x1011'i16 xor 0x0101'i16) == 0x1110
Source proc `==`(x, y: int): bool {.magic: "EqI", noSideEffect.}
- Source
proc `==`(x, y: int8): bool {.magic: "EqI", noSideEffect.}
- Source
proc `==`(x, y: int16): bool {.magic: "EqI", noSideEffect.}
- Source
proc `==`(x, y: int32): bool {.magic: "EqI", noSideEffect.}
- Source
proc `==`(x, y: int64): bool {.magic: "EqI", noSideEffect.}
- Compares two integers for equality. Source
proc `<=`(x, y: int): bool {.magic: "LeI", noSideEffect.}
- Source
proc `<=`(x, y: int8): bool {.magic: "LeI", noSideEffect.}
- Source
proc `<=`(x, y: int16): bool {.magic: "LeI", noSideEffect.}
- Source
proc `<=`(x, y: int32): bool {.magic: "LeI", noSideEffect.}
- Source
proc `<=`(x, y: int64): bool {.magic: "LeI", noSideEffect.}
- Returns true iff x is less than or equal to y. Source
proc `<`(x, y: int): bool {.magic: "LtI", noSideEffect.}
- Source
proc `<`(x, y: int8): bool {.magic: "LtI", noSideEffect.}
- Source
proc `<`(x, y: int16): bool {.magic: "LtI", noSideEffect.}
- Source
proc `<`(x, y: int32): bool {.magic: "LtI", noSideEffect.}
- Source
proc `<`(x, y: int64): bool {.magic: "LtI", noSideEffect.}
- Returns true iff x is less than y. Source
proc `+%`[IntMax32](x, y: IntMax32): IntMax32 {.magic: "AddU", noSideEffect.}
- Source
proc `+%`(x, y: int64): int64 {.magic: "AddU", noSideEffect.}
- 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
proc `-%`[IntMax32](x, y: IntMax32): IntMax32 {.magic: "SubU", noSideEffect.}
- Source
proc `-%`(x, y: int64): int64 {.magic: "SubU", noSideEffect.}
- 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
proc `*%`[IntMax32](x, y: IntMax32): IntMax32 {.magic: "MulU", noSideEffect.}
- Source
proc `*%`(x, y: int64): int64 {.magic: "MulU", noSideEffect.}
- 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
proc `/%`[IntMax32](x, y: IntMax32): IntMax32 {.magic: "DivU", noSideEffect.}
- Source
proc `/%`(x, y: int64): int64 {.magic: "DivU", noSideEffect.}
- 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
proc `%%`[IntMax32](x, y: IntMax32): IntMax32 {.magic: "ModU", noSideEffect.}
- Source
proc `%%`(x, y: int64): int64 {.magic: "ModU", noSideEffect.}
- 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
proc `<=%`[IntMax32](x, y: IntMax32): bool {.magic: "LeU", noSideEffect.}
- Source
proc `<=%`(x, y: int64): bool {.magic: "LeU64", noSideEffect.}
- treats x and y as unsigned and compares them. Returns true iff unsigned(x) <= unsigned(y). Source
proc `<%`[IntMax32](x, y: IntMax32): bool {.magic: "LtU", noSideEffect.}
- Source
proc `<%`(x, y: int64): bool {.magic: "LtU64", noSideEffect.}
- treats x and y as unsigned and compares them. Returns true iff unsigned(x) < unsigned(y). Source
proc `not`[T](x: T): T {.magic: "BitnotI", noSideEffect.}
- computes the bitwise complement of the integer x. Source
proc `shr`[T](x, y: T): T {.magic: "ShrI", noSideEffect.}
- computes the shift right operation of x and y. Source
proc `shl`[T](x, y: T): T {.magic: "ShlI", noSideEffect.}
- computes the shift left operation of x and y. Source
proc `and`[T](x, y: T): T {.magic: "BitandI", noSideEffect.}
- computes the bitwise and of numbers x and y. Source
proc `or`[T](x, y: T): T {.magic: "BitorI", noSideEffect.}
- computes the bitwise or of numbers x and y. Source
proc `xor`[T](x, y: T): T {.magic: "BitxorI", noSideEffect.}
- computes the bitwise xor of numbers x and y. Source
proc `==`[T](x, y: T): bool {.magic: "EqI", noSideEffect.}
- Compares two unsigned integers for equality. Source
proc `+`[T](x, y: T): T {.magic: "AddU", noSideEffect.}
- Binary + operator for unsigned integers. Source
proc `-`[T](x, y: T): T {.magic: "SubU", noSideEffect.}
- Binary - operator for unsigned integers. Source
proc `*`[T](x, y: T): T {.magic: "MulU", noSideEffect.}
- Binary * operator for unsigned integers. Source
proc `div`[T](x, y: T): T {.magic: "DivU", noSideEffect.}
-
computes the integer division. This is roughly the same as floor(x/y).
(7 div 5) == 2
Source proc `mod`[T](x, y: T): T {.magic: "ModU", noSideEffect.}
-
computes the integer modulo operation (remainder). This is the same as x - (x div y) * y.
(7 mod 5) == 2
Source proc `<=`[T](x, y: T): bool {.magic: "LeU", noSideEffect.}
- Returns true iff x <= y. Source
proc `<`[T](x, y: T): bool {.magic: "LtU", noSideEffect.}
- Returns true iff unsigned(x) < unsigned(y). Source
proc `+`(x: float32): float32 {.magic: "UnaryPlusF64", noSideEffect.}
- Source
proc `-`(x: float32): float32 {.magic: "UnaryMinusF64", noSideEffect.}
- Source
proc `+`(x, y: float32): float32 {.magic: "AddF64", noSideEffect.}
- Source
proc `-`(x, y: float32): float32 {.magic: "SubF64", noSideEffect.}
- Source
proc `*`(x, y: float32): float32 {.magic: "MulF64", noSideEffect.}
- Source
proc `/`(x, y: float32): float32 {.magic: "DivF64", noSideEffect.}
- Source
proc `+`(x: float): float {.magic: "UnaryPlusF64", noSideEffect.}
- Source
proc `-`(x: float): float {.magic: "UnaryMinusF64", noSideEffect.}
- Source
proc `+`(x, y: float): float {.magic: "AddF64", noSideEffect.}
- Source
proc `-`(x, y: float): float {.magic: "SubF64", noSideEffect.}
- Source
proc `*`(x, y: float): float {.magic: "MulF64", noSideEffect.}
- Source
proc `/`(x, y: float): float {.magic: "DivF64", noSideEffect.}
- computes the floating point division Source
proc `==`(x, y: float32): bool {.magic: "EqF64", noSideEffect.}
- Source
proc `<=`(x, y: float32): bool {.magic: "LeF64", noSideEffect.}
- Source
proc `<`(x, y: float32): bool {.magic: "LtF64", noSideEffect.}
- Source
proc `==`(x, y: float): bool {.magic: "EqF64", noSideEffect.}
- Source
proc `<=`(x, y: float): bool {.magic: "LeF64", noSideEffect.}
- Source
proc `<`(x, y: float): bool {.magic: "LtF64", noSideEffect.}
- Source
proc `*`[T](x, y: set[T]): set[T] {.magic: "MulSet", noSideEffect.}
- This operator computes the intersection of two sets. Source
proc `+`[T](x, y: set[T]): set[T] {.magic: "PlusSet", noSideEffect.}
- This operator computes the union of two sets. Source
proc `-`[T](x, y: set[T]): set[T] {.magic: "MinusSet", noSideEffect.}
- This operator computes the difference of two sets. Source
proc contains[T](x: set[T]; y: T): bool {.magic: "InSet", noSideEffect.}
-
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:
var s: set[range['a'..'z']] = {'a'..'c'} writeLine(stdout, 'b' in s)
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 proc contains[T](s: Slice[T]; value: T): bool {.noSideEffect, inline.}
-
Checks if value is within the range of s; returns true iff 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 proc `is`[T, S](x: T; y: S): bool {.magic: "Is", noSideEffect.}
-
Checks if T is of the same type as S
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 proc `of`[T, S](x: T; y: S): bool {.magic: "Of", noSideEffect.}
-
Checks if x has a type of y
assert(FloatingPointError of Exception) assert(DivByZeroError of Exception)
Source proc cmp[T](x, y: T): int {.procvar.}
-
Generic compare proc. Returns a value < 0 iff x < y, a value > 0 iff x > y and 0 iff x == y. This is useful for writing generic algorithms without performance loss. This generic implementation uses the == and < operators.
import algorithm echo sorted(@[4,2,6,5,8,7], cmp[int])
Source proc `@`[IDX, T](a: array[IDX, T]): seq[T] {.magic: "ArrToSeq", nosideeffect.}
- 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]. Source
proc setLen[T](s: var seq[T]; newlen: Natural) {.magic: "SetLengthSeq", noSideEffect.}
- sets the length of s to newlen. T may be any sequence type. If the current length is greater than the new length, s will be truncated. s cannot be nil! To initialize a sequence with a size, use newSeq instead. Source
proc setLen(s: var string; newlen: Natural) {.magic: "SetLengthStr", noSideEffect.}
-
sets the length of s to newlen. If the current length is greater than the new length, s will be truncated. s cannot be nil! To initialize a string with a size, use newString instead.
var myS = "Nim is great!!" myS.setLen(3) echo myS, " is fantastic!!"
Source proc newString(len: Natural): string {.magic: "NewString", importc: "mnewString", noSideEffect.}
- 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
proc newStringOfCap(cap: Natural): string {.magic: "NewStringOfCap", importc: "rawNewString", noSideEffect.}
- 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
proc `&`(x: string; y: char): string {.magic: "ConStrStr", noSideEffect, merge.}
-
Concatenates x with y
assert("ab" & 'c' == "abc")
Source proc `&`(x, y: char): string {.magic: "ConStrStr", noSideEffect, merge.}
-
Concatenates x and y into a string
assert('a' & 'b' == "ab")
Source proc `&`(x, y: string): string {.magic: "ConStrStr", noSideEffect, merge.}
-
Concatenates x and y
assert("ab" & "cd" == "abcd")
Source proc `&`(x: char; y: string): string {.magic: "ConStrStr", noSideEffect, merge.}
-
Concatenates x with y
assert('a' & "bc" == "abc")
Source proc add(x: var string; y: char) {.magic: "AppendStrCh", noSideEffect.}
-
Appends y to x in place
var tmp = "" tmp.add('a') tmp.add('b') assert(tmp == "ab")
Source proc add(x: var string; y: string) {.magic: "AppendStrStr", noSideEffect.}
-
Concatenates x and y in place
var tmp = "" tmp.add("ab") tmp.add("cd") assert(tmp == "abcd")
Source proc compileOption(option: string): bool {.magic: "CompileOption", noSideEffect.}
-
can be used to determine an on|off compile-time option. Example:
when compileOption("floatchecks"): echo "compiled with floating point NaN and Inf checks"
Source proc compileOption(option, arg: string): bool {.magic: "CompileOptionArg", noSideEffect.}
-
can be used to determine an enum compile-time option. Example:
when compileOption("opt", "size") and compileOption("gc", "boehm"): echo "compiled with optimization for size and uses Boehm's GC"
Source proc quit(errorcode: int = QuitSuccess) {.magic: "Exit", importc: "exit", header: "<stdlib.h>", noreturn.}
-
Stops the program immediately with an exit code.
Before stopping the program the "quit procedures" are called in the opposite order they were added with addQuitProc. quit never returns and ignores any exception that may have been raised by the quit procedures. It does not call the garbage collector to free all the memory, unless a quit procedure calls GC_fullCollect.
The proc quit(QuitSuccess) is called implicitly when your nim program finishes without incident. 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.
Source proc add[T](x: var seq[T]; y: T) {.magic: "AppendSeqElem", noSideEffect.}
- Source
proc add[T](x: var seq[T]; y: openArray[T]) {.noSideEffect.}
-
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.
var s: seq[string] = @["test2","test2"] s.add("test") #=> @[test2, test2, test]
Source proc shallowCopy[T](x: var T; y: T) {.noSideEffect, magic: "ShallowCopy".}
- 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
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.
var i = @[1,2,3,4,5] i.del(2) #=> @[1, 2, 5, 4]
Source proc delete[T](x: var seq[T]; i: Natural) {.noSideEffect.}
-
deletes the item at index i by moving x[i+1..] by one position. This is an O(n) operation.
var i = @[1,2,3,4,5] i.delete(2) #=> @[1, 2, 4, 5]
Source proc insert[T](x: var seq[T]; item: T; i = 0.Natural) {.noSideEffect.}
-
inserts item into x at position i.
var i = @[1,2,3,4,5] i.insert(2,4) #=> @[1, 2, 3, 4, 2, 5]
Source proc repr[T](x: T): string {.magic: "Repr", noSideEffect.}
-
takes any Nim variable and returns its string representation. It works even for complex data graphs with cycles. This is a great debugging tool.
var s: seq[string] = @["test2","test2"] var i = @[1,2,3,4,5] repr(s) #=> 0x1055eb050[0x1055ec050"test2", 0x1055ec078"test2"] repr(i) #=> 0x1055ed050[1, 2, 3, 4, 5]
Source proc toFloat(i: int): float {.magic: "ToFloat", noSideEffect, importc: "toFloat".}
- converts an integer i into a float. If the conversion fails, EInvalidValue is raised. However, on most platforms the conversion cannot fail. Source
proc toBiggestFloat(i: BiggestInt): BiggestFloat {.magic: "ToBiggestFloat", noSideEffect, importc: "toBiggestFloat".}
- converts an biggestint i into a biggestfloat. If the conversion fails, EInvalidValue is raised. However, on most platforms the conversion cannot fail. Source
proc toInt(f: float): int {.magic: "ToInt", noSideEffect, importc: "toInt".}
- converts a floating point number f into an int. Conversion rounds f if it does not contain an integer value. If the conversion fails (because f is infinite for example), EInvalidValue is raised. Source
proc toBiggestInt(f: BiggestFloat): BiggestInt {.magic: "ToBiggestInt", noSideEffect, importc: "toBiggestInt".}
- converts a biggestfloat f into a biggestint. Conversion rounds f if it does not contain an integer value. If the conversion fails (because f is infinite for example), EInvalidValue is raised. Source
proc addQuitProc(QuitProc: proc () {.noconv.}) {.importc: "atexit", header: "<stdlib.h>".}
-
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 proc copy(s: string; first = 0): string {.magic: "CopyStr", importc: "copyStr", noSideEffect, deprecated.}
- Source
proc copy(s: string; first, last: int): string {.magic: "CopyStrLast", importc: "copyStrLast", noSideEffect, deprecated.}
- 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). Deprecated since version 0.8.12: Use substr instead. Source
proc substr(s: string; first = 0): string {.magic: "CopyStr", importc: "copyStr", noSideEffect.}
- Source
proc substr(s: string; first, last: int): string {.magic: "CopyStrLast", importc: "copyStrLast", noSideEffect.}
- 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. Source
proc zeroMem(p: pointer; size: Natural) {.importc, noDecl, gcsafe, locks: 0.}
- overwrites the contents of the memory at p with the value 0. Exactly size bytes will be overwritten. Like any procedure dealing with raw memory this is unsafe. Source
proc copyMem(dest, source: pointer; size: Natural) {.importc: "memcpy", header: "<string.h>", gcsafe, locks: 0.}
- 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
proc moveMem(dest, source: pointer; size: Natural) {.importc: "memmove", header: "<string.h>", gcsafe, locks: 0.}
- 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
proc equalMem(a, b: pointer; size: Natural): bool {.importc: "equalMem", noDecl, noSideEffect.}
- 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
proc createU[](T: typedesc; size = 1.Positive): ptr T:type {.inline, gcsafe, locks: 0.}
- allocates a new memory block with at least T.sizeof * size bytes. The block has to be freed with resize(block, 0) or free(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. Source
proc create[](T: typedesc; size = 1.Positive): ptr T:type {.inline, gcsafe, locks: 0.}
- allocates a new memory block with at least T.sizeof * size bytes. The block has to be freed with resize(block, 0) or free(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
proc resize[T](p: ptr T; newSize: Natural): ptr T {.inline, gcsafe, locks: 0.}
- 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 free(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
- allocates a new memory block on the shared heap with at least T.sizeof * size bytes. The block has to be freed with resizeShared(block, 0) or freeShared(block). The block is not initialized, so reading from it before writing to it is undefined behaviour! Source
- allocates a new memory block on the shared heap with at least T.sizeof * size bytes. The block has to be freed with resizeShared(block, 0) or freeShared(block). The block is initialized with all bytes containing zero, so it is somewhat safer than createSharedU. Source
- grows or shrinks a given memory block on the heap. If p is nil then a new memory block is returned. In either way the block has at least T.sizeof * newSize bytes. If newSize == 0 and p is not nil resizeShared calls freeShared(p). In other cases the block has to be freed with freeShared. Source
- frees the memory allocated with createShared, createSharedU or resizeShared. This procedure is dangerous! If one forgets to free the memory a leak occurs; if one tries to access freed memory (or just freeing it twice!) a core dump may happen or other memory may be corrupted. Source
proc swap[T](a, b: var T) {.magic: "Swap", noSideEffect.}
- swaps the values a and b. This is often more efficient than tmp = a; a = b; b = tmp. Particularly useful for sorting algorithms. Source
proc `$`(x: int): string {.magic: "IntToStr", noSideEffect.}
- The stringify operator for an integer argument. Returns x converted to a decimal string. $ is Nim's general way of spelling toString. Source
proc `$`(x: int64): string {.magic: "Int64ToStr", noSideEffect.}
- The stringify operator for an integer argument. Returns x converted to a decimal string. Source
proc `$`(x: float): string {.magic: "FloatToStr", noSideEffect.}
- The stringify operator for a float argument. Returns x converted to a decimal string. Source
proc `$`(x: bool): string {.magic: "BoolToStr", noSideEffect.}
- The stringify operator for a boolean argument. Returns x converted to the string "false" or "true". Source
proc `$`(x: char): string {.magic: "CharToStr", noSideEffect.}
- The stringify operator for a character argument. Returns x converted to a string. Source
proc `$`(x: cstring): string {.magic: "CStrToStr", noSideEffect.}
- The stringify operator for a CString argument. Returns x converted to a string. Source
proc `$`(x: string): string {.magic: "StrToStr", noSideEffect.}
- The stringify operator for a string argument. Returns x as it is. This operator is useful for generic code, so that $expr also works if expr is already a string. Source
proc `$`[Enum](x: Enum): string {.magic: "EnumToStr", noSideEffect.}
- 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
proc getRefcount[T](x: ref T): int {.importc: "getRefcount", noSideEffect.}
- Source
proc getRefcount(x: string): int {.importc: "getRefcount", noSideEffect.}
- Source
proc getRefcount[T](x: seq[T]): int {.importc: "getRefcount", noSideEffect.}
- retrieves the reference count of an heap-allocated object. The value is implementation-dependent. Source
proc min(x, y: int): int {.magic: "MinI", noSideEffect, raises: [], tags: [].}
- Source
proc min(x, y: int8): int8 {.magic: "MinI", noSideEffect, raises: [], tags: [].}
- Source
proc min(x, y: int16): int16 {.magic: "MinI", noSideEffect, raises: [], tags: [].}
- Source
proc min(x, y: int32): int32 {.magic: "MinI", noSideEffect, raises: [], tags: [].}
- Source
proc min(x, y: int64): int64 {.magic: "MinI", noSideEffect, raises: [], tags: [].}
- The minimum value of two integers. Source
proc min[T](x: varargs[T]): T
- The minimum value of x. T needs to have a < operator. Source
proc max(x, y: int): int {.magic: "MaxI", noSideEffect, raises: [], tags: [].}
- Source
proc max(x, y: int8): int8 {.magic: "MaxI", noSideEffect, raises: [], tags: [].}
- Source
proc max(x, y: int16): int16 {.magic: "MaxI", noSideEffect, raises: [], tags: [].}
- Source
proc max(x, y: int32): int32 {.magic: "MaxI", noSideEffect, raises: [], tags: [].}
- Source
proc max(x, y: int64): int64 {.magic: "MaxI", noSideEffect, raises: [], tags: [].}
- The maximum value of two integers. Source
proc max[T](x: varargs[T]): T
- The maximum value of x. T needs to have a < operator. Source
proc abs(x: float): float {.magic: "AbsF64", noSideEffect, raises: [], tags: [].}
- Source
proc min(x, y: float): float {.magic: "MinF64", noSideEffect, raises: [], tags: [].}
- Source
proc max(x, y: float): float {.magic: "MaxF64", noSideEffect, raises: [], tags: [].}
- Source
proc clamp[T](x, a, b: T): T
-
limits the value x within the interval [a, b]
assert((1.4).clamp(0.0, 1.0) == 1.0) assert((0.5).clamp(0.0, 1.0) == 0.5)
Source proc isNil[T](x: seq[T]): bool {.noSideEffect, magic: "IsNil".}
- Source
proc isNil[T](x: ref T): bool {.noSideEffect, magic: "IsNil".}
- Source
proc isNil(x: string): bool {.noSideEffect, magic: "IsNil".}
- Source
proc isNil[T](x: ptr T): bool {.noSideEffect, magic: "IsNil".}
- Source
proc isNil(x: pointer): bool {.noSideEffect, magic: "IsNil".}
- Source
proc isNil(x: cstring): bool {.noSideEffect, magic: "IsNil".}
- Source
proc isNil[T](x: T): bool {.noSideEffect, magic: "IsNil".}
- Fast check whether x is nil. This is sometimes more efficient than == nil. Source
proc `==`[I, T](x, y: array[I, T]): bool
- Source
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
proc `&`[T](x, y: seq[T]): seq[T] {.noSideEffect.}
-
Concatenates two sequences. Requires copying of the sequences.
assert(@[1, 2, 3, 4] & @[5, 6] == @[1, 2, 3, 4, 5, 6])
Source proc `&`[T](x: seq[T]; y: T): seq[T] {.noSideEffect.}
-
Appends element y to the end of the sequence. Requires copying of the sequence
assert(@[1, 2, 3] & 4 == @[1, 2, 3, 4])
Source proc `&`[T](x: T; y: seq[T]): seq[T] {.noSideEffect.}
-
Prepends the element x to the beginning of the sequence. Requires copying of the sequence
assert(1 & @[2, 3, 4] == @[1, 2, 3, 4])
Source proc `==`[T](x, y: seq[T]): bool {.noSideEffect.}
- Generic equals operator for sequences: relies on a equals operator for the element type T. Source
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
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. Source
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. Source
proc `==`[T](x, y: T): bool
- generic == operator for tuples that is lifted from the components of x and y. Source
proc `<=`[T](x, y: T): bool
- generic <= operator for tuples that is lifted from the components of x and y. This implementation uses cmp. Source
proc `<`[T](x, y: T): bool
- generic < operator for tuples that is lifted from the components of x and y. This implementation uses cmp. Source
proc `$`[T](x: T): string
-
generic $ operator for tuples that is lifted from the components of x. Example:
$(23, 45) == "(23, 45)" $() == "()"
Source proc `$`[T](x: set[T]): string
-
generic $ operator for sets that is lifted from the components of x. Example:
${23, 45} == "{23, 45}"
Source proc `$`[T](x: seq[T]): string
-
generic $ operator for seqs that is lifted from the components of x. Example:
$(@[23, 45]) == "@[23, 45]"
Source proc GC_ref[T](x: ref T) {.magic: "GCref", gcsafe, locks: 0.}
- Source
proc GC_ref[T](x: seq[T]) {.magic: "GCref", gcsafe, locks: 0.}
- Source
proc GC_ref(x: string) {.magic: "GCref", gcsafe, locks: 0.}
- marks the object x as referenced, so that it will not be freed until it is unmarked via GC_unref. If called n-times for the same object x, n calls to GC_unref are needed to unmark x. Source
proc GC_unref[T](x: ref T) {.magic: "GCunref", gcsafe, locks: 0.}
- Source
proc GC_unref[T](x: seq[T]) {.magic: "GCunref", gcsafe, locks: 0.}
- Source
proc GC_unref(x: string) {.magic: "GCunref", gcsafe, locks: 0.}
- see the documentation of GC_ref. Source
proc add(x: var string; y: cstring) {.raises: [], tags: [].}
- Source
proc echo(x: varargs[typed, `$`]) {.magic: "Echo", tags: [WriteIOEffect], gcsafe, locks: 0, sideEffect.}
-
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 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
proc getTypeInfo[T](x: T): pointer {.magic: "GetTypeInfo", gcsafe, locks: 0.}
- get type information for x. Ordinary code should not use this, but the typeinfo module instead. Source
proc abs(x: int): int {.magic: "AbsI", noSideEffect, raises: [], tags: [].}
- Source
proc abs(x: int8): int8 {.magic: "AbsI", noSideEffect, raises: [], tags: [].}
- Source
proc abs(x: int16): int16 {.magic: "AbsI", noSideEffect, raises: [], tags: [].}
- Source
proc abs(x: int32): int32 {.magic: "AbsI", noSideEffect, raises: [], tags: [].}
- Source
proc abs(x: int64): int64 {.magic: "AbsI", noSideEffect, 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
proc cmp(x, y: string): int {.noSideEffect, procvar, raises: [], tags: [].}
- Compare proc for strings. More efficient than the generic version. Source
proc open(f: var File; filename: string; mode: FileMode = fmRead; bufSize: int = - 1): bool {. tags: [], gcsafe, locks: 0, raises: [].}
-
Opens a file named filename with given mode.
Default mode is readonly. Returns true iff the file could be opened. This throws no exception if the file could not be opened.
Source proc open(f: var File; filehandle: FileHandle; mode: FileMode = fmRead): bool {.tags: [], gcsafe, locks: 0, raises: [].}
-
Creates a File from a filehandle with given mode.
Default mode is readonly. Returns true iff the file could be opened.
Source proc open(filename: string; mode: FileMode = fmRead; bufSize: int = - 1): File {. raises: [Exception, IOError], tags: [].}
-
Opens a file named filename with given mode.
Default mode is readonly. Raises an IO exception if the file could not be opened.
Source proc reopen(f: File; filename: string; mode: FileMode = fmRead): bool {.tags: [], gcsafe, locks: 0, raises: [].}
-
reopens the file f with given filename and mode. This is often used to redirect the stdin, stdout or stderr file variables.
Default mode is readonly. Returns true iff the file could be reopened.
Source proc close(f: File) {.importc: "fclose", header: "<stdio.h>", tags: [].}
- Closes the file. Source
proc endOfFile(f: File): bool {.tags: [], gcsafe, locks: 0, raises: [].}
- Returns true iff f is at the end. Source
proc readChar(f: File): char {.importc: "fgetc", header: "<stdio.h>", tags: [ReadIOEffect].}
- Reads a single character from the stream f. Source
proc flushFile(f: File) {.importc: "fflush", header: "<stdio.h>", tags: [WriteIOEffect].}
- Flushes f's buffer. Source
proc readAll(file: File): TaintedString {.tags: [ReadIOEffect], gcsafe, locks: 0, raises: [Exception, IOError].}
-
Reads all data from the stream file.
Raises an IO exception in case of an error. It is an error if the current file position is not at the beginning of the file.
Source proc readFile(filename: string): TaintedString {.tags: [ReadIOEffect], gcsafe, locks: 0, raises: [Exception, IOError, Exception, IOError].}
-
Opens a file named filename for reading.
Then calls readAll and closes the file afterwards. Returns the string. Raises an IO exception in case of an error. If you need to call this inside a compile time macro you can use staticRead.
Source proc writeFile(filename, content: string) {.tags: [WriteIOEffect], gcsafe, locks: 0, raises: [Exception, IOError, Exception].}
- Opens a file named filename for writing. Then writes the content completely to the file and closes the file afterwards. Raises an IO exception in case of an error. Source
proc write(f: File; r: float32) {.tags: [WriteIOEffect], gcsafe, locks: 0, raises: [].}
- Source
proc write(f: File; i: int) {.tags: [WriteIOEffect], gcsafe, locks: 0, raises: [].}
- Source
proc write(f: File; i: BiggestInt) {.tags: [WriteIOEffect], gcsafe, locks: 0, raises: [].}
- Source
proc write(f: File; r: BiggestFloat) {.tags: [WriteIOEffect], gcsafe, locks: 0, raises: [].}
- Source
proc write(f: File; s: string) {.tags: [WriteIOEffect], gcsafe, locks: 0, raises: [IOError].}
- Source
proc write(f: File; b: bool) {.tags: [WriteIOEffect], gcsafe, locks: 0, raises: [Exception].}
- Source
proc write(f: File; c: char) {.tags: [WriteIOEffect], gcsafe, locks: 0, raises: [].}
- Source
proc write(f: File; c: cstring) {.tags: [WriteIOEffect], gcsafe, locks: 0, raises: [].}
- Source
proc write(f: File; a: varargs[string, `$`]) {.tags: [WriteIOEffect], gcsafe, locks: 0, raises: [Exception].}
- Writes a value to the file f. May throw an IO exception. Source
proc readLine(f: File): TaintedString {.tags: [ReadIOEffect], gcsafe, locks: 0, raises: [IOError].}
- reads a line of text from the file f. May throw an IO exception. A line of text may be delimited by LF or CRLF. The newline character(s) are not part of the returned string. Source
proc readLine(f: File; line: var TaintedString): bool {.tags: [ReadIOEffect], gcsafe, locks: 0, raises: [].}
- reads a line of text from the file f into line. line must not be nil! May throw an IO exception. A line of text may be delimited by LF or CRLF. The newline character(s) are not part of the returned string. Returns false if the end of the file has been reached, true otherwise. If false is returned line contains no new data. Source
proc writeLn[Ty](f: File; x: varargs[Ty, `$`]) {.inline, tags: [WriteIOEffect], gcsafe, locks: 0, deprecated.}
- Deprecated since version 0.11.4: Use writeLine instead. Source
proc writeLine[Ty](f: File; x: varargs[Ty, `$`]) {.inline, tags: [WriteIOEffect], gcsafe, locks: 0.}
- writes the values x to f and then writes "n". May throw an IO exception. Source
proc getFileSize(f: File): int64 {.tags: [ReadIOEffect], gcsafe, locks: 0, raises: [IOError].}
- retrieves the file size (in bytes) of f. Source
proc readBytes[](f: File; a: var openArray[int8 | uint8]; start, len: Natural): int {. tags: [ReadIOEffect], gcsafe, locks: 0.}
- reads len bytes into the buffer a starting at a[start]. Returns the actual number of bytes that have been read which may be less than len (if not as many bytes are remaining), but not greater. Source
proc readChars(f: File; a: var openArray[char]; start, len: Natural): int {. tags: [ReadIOEffect], gcsafe, locks: 0, raises: [].}
- reads len bytes into the buffer a starting at a[start]. Returns the actual number of bytes that have been read which may be less than len (if not as many bytes are remaining), but not greater. Source
proc readBuffer(f: File; buffer: pointer; len: Natural): int {.tags: [ReadIOEffect], gcsafe, locks: 0, raises: [].}
- reads len bytes into the buffer pointed to by buffer. Returns the actual number of bytes that have been read which may be less than len (if not as many bytes are remaining), but not greater. Source
proc writeBytes[](f: File; a: openArray[int8 | uint8]; start, len: Natural): int {. tags: [WriteIOEffect], gcsafe, locks: 0.}
- writes the bytes of a[start..start+len-1] to the file f. Returns the number of actual written bytes, which may be less than len in case of an error. Source
proc writeChars(f: File; a: openArray[char]; start, len: Natural): int {. tags: [WriteIOEffect], gcsafe, locks: 0, raises: [Exception].}
- writes the bytes of a[start..start+len-1] to the file f. Returns the number of actual written bytes, which may be less than len in case of an error. Source
proc writeBuffer(f: File; buffer: pointer; len: Natural): int {.tags: [WriteIOEffect], gcsafe, locks: 0, raises: [].}
- writes the bytes of buffer pointed to by the parameter buffer to the file f. Returns the number of actual written bytes, which may be less than len in case of an error. Source
proc setFilePos(f: File; pos: int64) {.gcsafe, locks: 0, raises: [IOError], tags: [].}
- sets the position of the file pointer that is used for read/write operations. The file's first byte has the index zero. Source
proc getFilePos(f: File): int64 {.gcsafe, locks: 0, raises: [IOError], tags: [].}
- retrieves the current position of the file pointer that is used to read from the file f. The file's first byte has the index zero. Source
proc getFileHandle(f: File): FileHandle {.importc: "fileno", header: "<stdio.h>".}
- returns the OS file handle of the file f. This is only useful for platform specific programming. Source
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
proc cstringArrayToSeq(a: cstringArray): seq[string] {.raises: [], tags: [].}
- converts a cstringArray to a seq[string]. a is supposed to be terminated by nil. Source
proc allocCStringArray(a: openArray[string]): cstringArray {.raises: [Exception], tags: [].}
- creates a NULL terminated cstringArray from a. The result has to be freed with deallocCStringArray after it's not needed anymore. Source
proc deallocCStringArray(a: cstringArray) {.raises: [Exception], tags: [].}
- frees a NULL terminated cstringArray. Source
proc atomicInc(memLoc: var int; x: int = 1): int {.inline, discardable, gcsafe, locks: 0, raises: [], tags: [].}
- atomic increment of memLoc. Returns the value after the operation. Source
proc atomicDec(memLoc: var int; x: int = 1): int {.inline, discardable, gcsafe, locks: 0, raises: [], tags: [].}
- atomic decrement of memLoc. Returns the value after the operation. Source
proc addAndFetch(p: ptr int; val: int): int {.inline, raises: [], tags: [].}
- Source
proc atomicInc(memLoc: var int; x: int = 1): int {.inline, discardable, gcsafe, locks: 0, raises: [], tags: [].}
- atomic increment of memLoc. Returns the value after the operation. Source
proc atomicDec(memLoc: var int; x: int = 1): int {.inline, discardable, gcsafe, locks: 0, raises: [], tags: [].}
- atomic decrement of memLoc. Returns the value after the operation. Source
proc cas[T](p: ptr T; oldValue, newValue: T): bool {. importc: "__sync_bool_compare_and_swap", nodecl.}
- Source
proc cpuRelax() {.inline, raises: [], tags: [].}
- Source
proc setControlCHook(hook: proc () {.noconv.} not nil) {.raises: [Exception], tags: [RootEffect].}
- allows you to override the behaviour of your application when CTRL+C is pressed. Only one such hook is supported. Source
proc writeStackTrace() {.tags: [WriteIOEffect], raises: [Exception].}
- writes the current stack trace to stderr. This is only works for debug builds. Source
proc getStackTrace(): string {.raises: [], tags: [].}
- gets the current stack trace. This only works for debug builds. Source
proc getStackTrace(e: ref Exception): string {.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
proc getFrame(): PFrame {.compilerproc, inline, raises: [], tags: [].}
- Source
proc setFrame(s: PFrame) {.compilerproc, inline, raises: [], tags: [].}
- Source
proc stackTraceAvailable(): bool {.raises: [], tags: [].}
- Source
proc stackTraceAvailable(): bool {.raises: [], tags: [].}
- Source
proc writeStackTrace() {.tags: [WriteIOEffect], raises: [Exception].}
- writes the current stack trace to stderr. This is only works for debug builds. Source
proc getStackTrace(): string {.raises: [], tags: [].}
- gets the current stack trace. This only works for debug builds. Source
proc getStackTrace(e: ref Exception): string {.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
proc setControlCHook(hook: proc () {.noconv.} not nil) {.raises: [Exception], tags: [RootEffect].}
- allows you to override the behaviour of your application when CTRL+C is pressed. Only one such hook is supported. Source
proc iterToProc[](iter: typed; envType: typedesc; procName: untyped) {.magic: "Plugin", compileTime.}
- Source
proc alloc(size: Natural): pointer {.noconv, gcsafe, tags: [], gcsafe, locks: 0, raises: [Exception].}
- 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. Source
proc alloc0(size: Natural): pointer {.noconv, gcsafe, tags: [], gcsafe, locks: 0, raises: [Exception].}
- 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
proc dealloc(p: pointer) {.noconv, gcsafe, tags: [], gcsafe, locks: 0, raises: [Exception].}
- frees the memory allocated with alloc, alloc0 or realloc. 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
proc realloc(p: pointer; newSize: Natural): pointer {.noconv, gcsafe, tags: [], gcsafe, locks: 0, raises: [Exception].}
- 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. The allocated memory belongs to its allocating thread! Use reallocShared to reallocate from a shared heap. Source
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
proc getTotalMem(): int {.gcsafe, raises: [], tags: [].}
- returns the number of bytes that are owned by the process. Source
proc getOccupiedMem(): int {.gcsafe, raises: [], tags: [].}
- returns the number of bytes that are owned by the process and hold data. Source
- allocates a new memory block on the shared heap with at least size bytes. The block has to be freed with reallocShared(block, 0) or deallocShared(block). The block is not initialized, so reading from it before writing to it is undefined behaviour! Source
- allocates a new memory block on the shared heap with at least size bytes. The block has to be freed with reallocShared(block, 0) or deallocShared(block). The block is initialized with all bytes containing zero, so it is somewhat safer than allocShared. Source
- frees the memory allocated with allocShared, allocShared0 or reallocShared. This procedure is dangerous! If one forgets to free the memory a leak occurs; if one tries to access freed memory (or just freeing it twice!) a core dump may happen or other memory may be corrupted. Source
- grows or shrinks a given memory block on the heap. If p is nil then a new memory block is returned. In either way the block has at least newSize bytes. If newSize == 0 and p is not nil reallocShared calls deallocShared(p). In other cases the block has to be freed with deallocShared. Source
proc GC_addCycleRoot[T](p: ref T) {.inline.}
- adds 'p' to the cycle candidate set for the cycle collector. It is necessary if you used the 'acyclic' pragma for optimization purposes and need to break cycles manually. Source
proc gcInvariant() {.raises: [], tags: [].}
- Source
proc setupForeignThreadGc() {.raises: [Exception], tags: [RootEffect].}
- call this if you registered a callback that will be run from a thread not under your control. This has a cheap thread-local guard, so the GC for this thread will only be initialized once per thread, no matter how often it is called. Source
proc GC_disable() {.gcsafe, inline, gcsafe, locks: 0, raises: [], tags: [].}
- disables the GC. If called n-times, n calls to GC_enable are needed to reactivate the GC. Note that in most circumstances one should only disable the mark and sweep phase with GC_disableMarkAndSweep. Source
proc GC_enable() {.gcsafe, inline, gcsafe, locks: 0, raises: [], tags: [].}
- enables the GC again. Source
proc GC_setStrategy(strategy: GC_Strategy) {.gcsafe, deprecated, gcsafe, locks: 0, raises: [], tags: [].}
- tells the GC the desired strategy for the application. Deprecated since version 0.8.14. This has always been a nop. Source
proc GC_enableMarkAndSweep() {.gcsafe, gcsafe, locks: 0, raises: [], tags: [].}
- Source
proc GC_disableMarkAndSweep() {.gcsafe, gcsafe, locks: 0, raises: [], tags: [].}
- the current implementation uses a reference counting garbage collector with a seldomly run mark and sweep phase to free cycles. The mark and sweep phase may take a long time and is not needed if the application does not create cycles. Thus the mark and sweep phase can be deactivated and activated separately from the rest of the GC. Source
proc GC_fullCollect() {.gcsafe, gcsafe, locks: 0, raises: [Exception], tags: [RootEffect].}
- forces a full garbage collection pass. Ordinary code does not need to call this (and should not). Source
proc GC_getStatistics(): string {.gcsafe, gcsafe, locks: 0, raises: [], tags: [].}
- returns an informative string about the GC's activity. This may be useful for tweaking. Source
proc write(f: File; c: cstring) {.tags: [WriteIOEffect], gcsafe, locks: 0, raises: [].}
- Source
proc readLine(f: File; line: var TaintedString): bool {.tags: [ReadIOEffect], gcsafe, locks: 0, raises: [].}
- reads a line of text from the file f into line. line must not be nil! May throw an IO exception. A line of text may be delimited by LF or CRLF. The newline character(s) are not part of the returned string. Returns false if the end of the file has been reached, true otherwise. If false is returned line contains no new data. Source
proc readLine(f: File): TaintedString {.tags: [ReadIOEffect], gcsafe, locks: 0, raises: [IOError].}
- reads a line of text from the file f. May throw an IO exception. A line of text may be delimited by LF or CRLF. The newline character(s) are not part of the returned string. Source
proc write(f: File; i: int) {.tags: [WriteIOEffect], gcsafe, locks: 0, raises: [].}
- Source
proc write(f: File; i: BiggestInt) {.tags: [WriteIOEffect], gcsafe, locks: 0, raises: [].}
- Source
proc write(f: File; b: bool) {.tags: [WriteIOEffect], gcsafe, locks: 0, raises: [Exception].}
- Source
proc write(f: File; r: float32) {.tags: [WriteIOEffect], gcsafe, locks: 0, raises: [].}
- Source
proc write(f: File; r: BiggestFloat) {.tags: [WriteIOEffect], gcsafe, locks: 0, raises: [].}
- Source
proc write(f: File; c: char) {.tags: [WriteIOEffect], gcsafe, locks: 0, raises: [].}
- Source
proc write(f: File; a: varargs[string, `$`]) {.tags: [WriteIOEffect], gcsafe, locks: 0, raises: [Exception].}
- Writes a value to the file f. May throw an IO exception. Source
proc readAll(file: File): TaintedString {.tags: [ReadIOEffect], gcsafe, locks: 0, raises: [Exception, IOError].}
-
Reads all data from the stream file.
Raises an IO exception in case of an error. It is an error if the current file position is not at the beginning of the file.
Source proc readFile(filename: string): TaintedString {.tags: [ReadIOEffect], gcsafe, locks: 0, raises: [Exception, IOError, Exception, IOError].}
-
Opens a file named filename for reading.
Then calls readAll and closes the file afterwards. Returns the string. Raises an IO exception in case of an error. If you need to call this inside a compile time macro you can use staticRead.
Source proc writeFile(filename, content: string) {.tags: [WriteIOEffect], gcsafe, locks: 0, raises: [Exception, IOError, Exception].}
- Opens a file named filename for writing. Then writes the content completely to the file and closes the file afterwards. Raises an IO exception in case of an error. Source
proc endOfFile(f: File): bool {.tags: [], gcsafe, locks: 0, raises: [].}
- Returns true iff f is at the end. Source
proc writeLn[Ty](f: File; x: varargs[Ty, `$`]) {.inline, tags: [WriteIOEffect], gcsafe, locks: 0, deprecated.}
- Deprecated since version 0.11.4: Use writeLine instead. Source
proc writeLine[Ty](f: File; x: varargs[Ty, `$`]) {.inline, tags: [WriteIOEffect], gcsafe, locks: 0.}
- writes the values x to f and then writes "n". May throw an IO exception. Source
proc len(w: WideCString): int {.raises: [], tags: [].}
- returns the length of a widestring. This traverses the whole string to find the binary zero end marker! Source
proc newWideCString(source: cstring; L: int): WideCString {.raises: [], tags: [].}
- Source
proc newWideCString(s: cstring): WideCString {.raises: [], tags: [].}
- Source
proc newWideCString(s: string): WideCString {.raises: [], tags: [].}
- Source
proc `$`(w: WideCString; estimate: int; replacement: int = 0x0000FFFD): string {. raises: [], tags: [].}
- Source
proc `$`(s: WideCString): string {.raises: [], tags: [].}
- Source
proc open(f: var File; filename: string; mode: FileMode = fmRead; bufSize: int = - 1): bool {. tags: [], gcsafe, locks: 0, raises: [].}
-
Opens a file named filename with given mode.
Default mode is readonly. Returns true iff the file could be opened. This throws no exception if the file could not be opened.
Source proc reopen(f: File; filename: string; mode: FileMode = fmRead): bool {.tags: [], gcsafe, locks: 0, raises: [].}
-
reopens the file f with given filename and mode. This is often used to redirect the stdin, stdout or stderr file variables.
Default mode is readonly. Returns true iff the file could be reopened.
Source proc open(f: var File; filehandle: FileHandle; mode: FileMode = fmRead): bool {.tags: [], gcsafe, locks: 0, raises: [].}
-
Creates a File from a filehandle with given mode.
Default mode is readonly. Returns true iff the file could be opened.
Source proc readBuffer(f: File; buffer: pointer; len: Natural): int {.tags: [ReadIOEffect], gcsafe, locks: 0, raises: [].}
- reads len bytes into the buffer pointed to by buffer. Returns the actual number of bytes that have been read which may be less than len (if not as many bytes are remaining), but not greater. Source
proc readBytes[](f: File; a: var openArray[int8 | uint8]; start, len: Natural): int {. tags: [ReadIOEffect], gcsafe, locks: 0.}
- reads len bytes into the buffer a starting at a[start]. Returns the actual number of bytes that have been read which may be less than len (if not as many bytes are remaining), but not greater. Source
proc readChars(f: File; a: var openArray[char]; start, len: Natural): int {. tags: [ReadIOEffect], gcsafe, locks: 0, raises: [].}
- reads len bytes into the buffer a starting at a[start]. Returns the actual number of bytes that have been read which may be less than len (if not as many bytes are remaining), but not greater. Source
proc writeBytes[](f: File; a: openArray[int8 | uint8]; start, len: Natural): int {. tags: [WriteIOEffect], gcsafe, locks: 0.}
- writes the bytes of a[start..start+len-1] to the file f. Returns the number of actual written bytes, which may be less than len in case of an error. Source
proc writeChars(f: File; a: openArray[char]; start, len: Natural): int {. tags: [WriteIOEffect], gcsafe, locks: 0, raises: [Exception].}
- writes the bytes of a[start..start+len-1] to the file f. Returns the number of actual written bytes, which may be less than len in case of an error. Source
proc writeBuffer(f: File; buffer: pointer; len: Natural): int {.tags: [WriteIOEffect], gcsafe, locks: 0, raises: [].}
- writes the bytes of buffer pointed to by the parameter buffer to the file f. Returns the number of actual written bytes, which may be less than len in case of an error. Source
proc write(f: File; s: string) {.tags: [WriteIOEffect], gcsafe, locks: 0, raises: [IOError].}
- Source
proc setFilePos(f: File; pos: int64) {.gcsafe, locks: 0, raises: [IOError], tags: [].}
- sets the position of the file pointer that is used for read/write operations. The file's first byte has the index zero. Source
proc getFilePos(f: File): int64 {.gcsafe, locks: 0, raises: [IOError], tags: [].}
- retrieves the current position of the file pointer that is used to read from the file f. The file's first byte has the index zero. Source
proc getFileSize(f: File): int64 {.tags: [ReadIOEffect], gcsafe, locks: 0, raises: [IOError].}
- retrieves the file size (in bytes) of f. Source
proc `$`(x: uint64): string {.noSideEffect, raises: [], tags: [].}
- The stringify operator for an unsigned integer argument. Returns x converted to a decimal string. Source
proc getCurrentException(): ref Exception {.compilerproc, inline, gcsafe, locks: 0, raises: [], tags: [].}
- retrieves the current exception; if there is none, nil is returned. Source
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
proc onRaise(action: proc (e: ref Exception): bool {.closure.}) {.raises: [], tags: [].}
- can be used in a try statement to setup a Lisp-like condition system: This prevents the 'raise' statement to raise an exception but instead calls action. If action returns false, the exception has been handled and does not propagate further through the call stack. Source
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 proc likely(val: bool): bool {.importc: "likely", nodecl, nosideeffect.}
-
Hints the optimizer that val is likely going to be true.
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 likely(value <= 100): process(value) else: echo "Value too big!"
Source proc unlikely(val: bool): bool {.importc: "unlikely", nodecl, nosideeffect.}
-
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)
Source proc rawProc[T](x: T): pointer {.noSideEffect, inline.}
- retrieves the raw proc pointer of the closure x. This is useful for interfacing closures with C. Source
proc rawEnv[T](x: T): pointer {.noSideEffect, inline.}
- retrieves the raw environment pointer of the closure x. This is useful for interfacing closures with C. Source
proc finished[T](x: T): bool {.noSideEffect, inline.}
- can be used to determine if a first class iterator has finished. Source
proc quit(errormsg: string; errorcode = QuitFailure) {.noReturn, raises: [], tags: [].}
- a shorthand for echo(errormsg); quit(errorcode). Source
proc `/`(x, y: int): float {.inline, noSideEffect, raises: [], tags: [].}
- integer division that results in a float. Source
proc `[]`(s: string; x: Slice[int]): string {.inline, raises: [], tags: [].}
- slice operation for strings. Source
proc `[]=`(s: var string; x: Slice[int]; b: string) {.raises: [], tags: [].}
-
slice assignment for strings. If b.len is not exactly the number of elements that are referred to by x, a splice is performed:
var s = "abcdef" s[1 .. ^2] = "xyz" assert s == "axyzf"
Source proc `[]`[Idx, T](a: array[Idx, T]; x: Slice[int]): seq[T]
- slice operation for arrays. Source
proc `[]=`[Idx, T](a: var array[Idx, T]; x: Slice[int]; b: openArray[T])
- slice assignment for arrays. Source
proc `[]`[Idx, T](a: array[Idx, T]; x: Slice[Idx]): seq[T]
- slice operation for arrays. Source
proc `[]=`[Idx, T](a: var array[Idx, T]; x: Slice[Idx]; b: openArray[T])
- slice assignment for arrays. Source
proc `[]`[T](s: seq[T]; x: Slice[int]): seq[T]
- slice operation for sequences. Source
proc `[]=`[T](s: var seq[T]; x: Slice[int]; 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. Source
proc slurp(filename: string): string {.magic: "Slurp".}
- This is an alias for staticRead. Source
proc staticRead(filename: string): string {.magic: "Slurp".}
-
Compile-time readFile proc for easy resource embedding:
const myResource = staticRead"mydatafile.bin"
slurp is an alias for staticRead.
Source proc gorge(command: string; input = ""; cache = ""): string {.magic: "StaticExec", raises: [], tags: [].}
- This is an alias for staticExec. Source
proc staticExec(command: string; input = ""; cache = ""): string {.magic: "StaticExec", raises: [], tags: [].}
-
Executes an external process at compile-time. 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 wether the entry in the cache is still valid. You can use versioning information for cache:
const stateMachine = staticExec("dfaoptimizer", "input", "0.8.0")
Source proc `+=`[T](x: var T; y: T) {.magic: "Inc", noSideEffect.}
- Increments an ordinal Source
proc `-=`[T](x: var T; y: T) {.magic: "Dec", noSideEffect.}
- Decrements an ordinal Source
proc `*=`[T](x: var T; y: T) {.inline, noSideEffect.}
- Binary *= operator for ordinals Source
proc `+=`[T](x: var T; y: T) {.inline, noSideEffect.}
- Increments in placee a floating point number Source
proc `-=`[T](x: var T; y: T) {.inline, noSideEffect.}
- Decrements in place a floating point number Source
proc `*=`[T](x: var T; y: T) {.inline, noSideEffect.}
- Multiplies in place a floating point number Source
proc `/=`(x: var float64; y: float64) {.inline, noSideEffect, raises: [], tags: [].}
- Divides in place a floating point number Source
proc `/=`[T](x: var T; y: T) {.inline, noSideEffect.}
- Divides in place a floating point number Source
proc `&=`(x: var string; y: string) {.magic: "AppendStrStr", noSideEffect.}
- Source
proc astToStr[T](x: T): string {.magic: "AstToStr", noSideEffect.}
- converts the AST of x into a string representation. This is very useful for debugging. Source
proc instantiationInfo(index = - 1; fullPaths = false): tuple[filename: string, line: int] {. magic: "InstantiationInfo", noSideEffect.}
-
provides access to the compiler's instantiation stack line information.
This proc is mostly useful for meta programming (eg. assert template) to retrieve information about the current filename and line number. Example:
import strutils template testException(exception, code: expr): stmt = 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(IndexError, tester(30)) testException(IndexError, tester(1)) # --> Test failure at example.nim:20 with 'tester(1)'
Source proc raiseAssert(msg: string) {.noinline, raises: [AssertionError], tags: [].}
- Source
proc failedAssertImpl(msg: string) {.raises: [], tags: [].}
- Source
proc shallow[T](s: var seq[T]) {.noSideEffect, inline.}
- marks a sequence s as shallow. Subsequent assignments will not perform deep copies of s. This is only useful for optimization purposes. Source
proc shallow(s: var string) {.noSideEffect, inline, raises: [], tags: [].}
- marks a string s as shallow. Subsequent assignments will not perform deep copies of s. This is only useful for optimization purposes. Source
proc insert(x: var string; item: string; i = 0.Natural) {.noSideEffect, raises: [], tags: [].}
- inserts item into x at position i. Source
proc compiles(x: expr): 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 not compiles(3 + 4): echo "'+' for integers is available"
Source proc safeAdd[T](x: var seq[T]; y: T) {.noSideEffect.}
- Adds y to x unless x is not yet initialized; in that case, x becomes @[y] Source
proc safeAdd(x: var string; y: char) {.raises: [], tags: [].}
- Adds y to x. If x is nil it is initialized to "" Source
proc safeAdd(x: var string; y: string) {.raises: [], tags: [].}
- Adds y to x unless x is not yet initalized; in that case, x becomes y Source
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 constrast 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 proc deepCopy[T](x: var T; y: T) {.noSideEffect, magic: "DeepCopy".}
- performs a deep copy of x. This is also used by the code generator for the implementation of spawn. Source
proc procCall(x: expr) {.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 proc `^`[T](x: int; y: openArray[T]): int {.noSideEffect, magic: "Roof".}
- Source
proc `^`(x: int): int {.noSideEffect, magic: "Roof", raises: [], tags: [].}
- builtin roof operator that can be used for convenient array access. a[^x] is rewritten to a[a.len-x]. However currently the a expression must not have side effects for this to compile. Note that since this is a builtin, it automatically works for all kinds of overloaded [] or []= accessors. Source
proc xlen(x: string): int {.magic: "XLenStr", noSideEffect, raises: [], tags: [].}
- Source
proc xlen[T](x: seq[T]): int {.magic: "XLenSeq", noSideEffect.}
- returns the length of a sequence or a string without testing for 'nil'. This is an optimization that rarely makes sense. Source
Iterators
iterator countdown[T](a, b: T; step = 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. Source
iterator countup[S, T](a: S; b: T; step = 1): T {.inline.}
- Counts from ordinal value a up to b (inclusive) with the given step count. S, 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. Source
iterator `..`[S, T](a: S; b: T): T {.inline.}
- An alias for countup. Source
iterator `||`[S, T](a: S; b: T; annotation = ""): T {.inline, magic: "OmpParFor", sideEffect.}
- parallel loop iterator. Same as .. but the loop may run in parallel. annotation is an additional annotation for the code generator to use. Note that the compiler maps that to the #pragma omp parallel for construct of OpenMP and as such isn't aware of the parallelism in your code! Be careful! Later versions of || will get proper support by Nim's code generator and GC. Source
iterator items[T](a: openArray[T]): T {.inline.}
- iterates over each item of a. Source
iterator mitems[T](a: var openArray[T]): var T {.inline.}
- iterates over each item of a so that you can modify the yielded value. Source
iterator items[IX, T](a: array[IX, T]): T {.inline.}
- iterates over each item of a. Source
iterator mitems[IX, T](a: var array[IX, T]): var T {.inline.}
- iterates over each item of a so that you can modify the yielded value. Source
iterator items[T](a: set[T]): T {.inline.}
- iterates over each element of a. items iterates only over the elements that are really in the set (and not over the ones the set is able to hold). Source
iterator items(a: cstring): char {.inline, raises: [], tags: [].}
- iterates over each item of a. Source
iterator mitems(a: var cstring): var char {.inline, raises: [], tags: [].}
- iterates over each item of a so that you can modify the yielded value. Source
iterator items[](E: typedesc[enum]): E:type
- iterates over the values of the enum E. Source
iterator items[T](s: Slice[T]): T
- iterates over the slice s, yielding each value between s.a and s.b (inclusively). Source
iterator pairs[T](a: openArray[T]): tuple[key: int, val: T] {.inline.}
- iterates over each item of a. Yields (index, a[index]) pairs. Source
iterator mpairs[T](a: var openArray[T]): tuple[key: int, val: var T] {.inline.}
- iterates over each item of a. Yields (index, a[index]) pairs. a[index] can be modified. Source
iterator pairs[IX, T](a: array[IX, T]): tuple[key: IX, val: T] {.inline.}
- iterates over each item of a. Yields (index, a[index]) pairs. Source
iterator mpairs[IX, T](a: var array[IX, T]): tuple[key: IX, val: var T] {.inline.}
- iterates over each item of a. Yields (index, a[index]) pairs. a[index] can be modified. Source
iterator pairs[T](a: seq[T]): tuple[key: int, val: T] {.inline.}
- iterates over each item of a. Yields (index, a[index]) pairs. Source
iterator mpairs[T](a: var seq[T]): tuple[key: int, val: var T] {.inline.}
- iterates over each item of a. Yields (index, a[index]) pairs. a[index] can be modified. Source
iterator pairs(a: string): tuple[key: int, val: char] {.inline, raises: [], tags: [].}
- iterates over each item of a. Yields (index, a[index]) pairs. Source
iterator mpairs(a: var string): tuple[key: int, val: var char] {.inline, raises: [], tags: [].}
- iterates over each item of a. Yields (index, a[index]) pairs. a[index] can be modified. Source
iterator pairs(a: cstring): tuple[key: int, val: char] {.inline, raises: [], tags: [].}
- iterates over each item of a. Yields (index, a[index]) pairs. Source
iterator mpairs(a: var cstring): tuple[key: int, val: var char] {.inline, raises: [], tags: [].}
- iterates over each item of a. Yields (index, a[index]) pairs. a[index] can be modified. Source
iterator fields[T](x: T): RootObj {.magic: "Fields", noSideEffect.}
- iterates over every field of x. Warning: This really transforms the 'for' and unrolls the loop. The current implementation also has a bug that affects symbol binding in the loop body. Source
iterator fields[S, T](x: S; y: T): tuple[a, b: expr] {.magic: "Fields", noSideEffect.}
- iterates over every field of x and y. Warning: This is really transforms the 'for' and unrolls the loop. The current implementation also has a bug that affects symbol binding in the loop body. Source
iterator fieldPairs[T](x: T): RootObj {.magic: "FieldPairs", noSideEffect.}
-
Iterates over every field of x returning their name and value.
When you iterate over objects with different field types you have to use the compile time when instead of a runtime if to select the code you want to run for each type. To perform the comparison use the is operator. Example:
type Custom = object foo: string bar: bool proc `$`(x: Custom): string = result = "Custom:" for name, value in x.fieldPairs: when value is bool: result.add("\n\t" & name & " is " & $value) else: if value.isNil: result.add("\n\t" & name & " (nil)") else: result.add("\n\t" & name & " '" & value & "'")
Another way to do the same without when is to leave the task of picking the appropriate code to a secondary proc which you overload for each field type and pass the value to.
Warning: This really transforms the 'for' and unrolls the loop. The current implementation also has a bug that affects symbol binding in the loop body.
Source iterator fieldPairs[S, T](x: S; y: T): tuple[a, b: expr] {.magic: "FieldPairs", noSideEffect.}
- iterates over every field of x and y. Warning: This really transforms the 'for' and unrolls the loop. The current implementation also has a bug that affects symbol binding in the loop body. Source
iterator lines(filename: string): TaintedString {.tags: [ReadIOEffect], raises: [Exception, IOError].}
-
Iterates over any line in the file named filename.
If the file does not exist EIO is raised. The trailing newline character(s) are removed from the iterated lines. Example:
import strutils proc transformLetters(filename: string) = var buffer = "" for line in filename.lines: buffer.add(line.replace("a", "0") & '\x0A') writeFile(filename, buffer)
Source iterator lines(f: File): TaintedString {.tags: [ReadIOEffect], raises: [].}
-
Iterate over any line in the file f.
The trailing newline character(s) are removed from the iterated lines. Example:
proc countZeros(filename: File): tuple[lines, zeros: int] = for line in filename.lines: for letter in line: if letter == '0': result.zeros += 1 result.lines += 1
Source iterator items[T](a: seq[T]): T {.inline.}
- iterates over each item of a. Source
iterator mitems[T](a: var seq[T]): var T {.inline.}
- iterates over each item of a so that you can modify the yielded value. Source
iterator items(a: string): char {.inline, raises: [], tags: [].}
- iterates over each item of a. Source
iterator mitems(a: var string): var char {.inline, raises: [], tags: [].}
- iterates over each item of a so that you can modify the yielded value. Source
Templates
template `!=`(x, y: expr): expr {.immediate.}
- unequals operator. This is a shorthand for not (x == y). Source
template `>=`(x, y: expr): expr {.immediate.}
- "is greater or equals" operator. This is the same as y <= x. Source
template `>`(x, y: expr): expr {.immediate.}
- "is greater" operator. This is the same as y < x. Source
template incl[T](s: var set[T]; flags: set[T])
- includes the set of flags to the set x. Source
template excl[T](s: var set[T]; flags: set[T])
- excludes the set of flags to x. Source
template `in`(x, y: expr): expr {.immediate, dirty.}
-
Sugar for contains
assert(1 in (1..3) == true) assert(5 in (1..3) == false)
Source template `notin`(x, y: expr): expr {.immediate, dirty.}
-
Sugar for not containing
assert(1 notin (1..3) == false) assert(5 notin (1..3) == true)
Source template `isnot`(x, y: expr): expr {.immediate.}
- Negated version of is. Equivalent to not(x is y). Source
template `>=%`(x, y: expr): expr {.immediate.}
- treats x and y as unsigned and compares them. Returns true iff unsigned(x) >= unsigned(y). Source
template `>%`(x, y: expr): expr {.immediate.}
- treats x and y as unsigned and compares them. Returns true iff unsigned(x) > unsigned(y). Source
template accumulateResult(iter: expr)
- helps to convert an iterator to a proc. Source
template newException[](exceptn: typedesc; message: string): expr
- creates an exception object of type exceptn and sets its msg field to message. Returns the new exception object. Source
template stdmsg(): File
- Template which expands to either stdout or stderr depending on useStdoutAsStdmsg compile-time switch. Source
template currentSourcePath(): string
- returns the full file-system path of the current source Source
template assert(cond: bool; msg = "")
- Raises AssertionError with msg if cond is false. Note that AssertionError is hidden from the effect system, so it doesn't produce {.raises: [AssertionError].}. This exception is only supposed to be caught by unit testing frameworks. The compiler may not generate any code at all for assert if it is advised to do so through the -d:release or --assertions:off command line switches. Source
template doAssert(cond: bool; msg = "")
- same as assert but is always turned on and not affected by the --assertions command line switch. Source
template onFailedAssert(msg: expr; code: stmt): stmt {.dirty, immediate.}
-
Sets an assertion failure handler that will intercept any assert statements following onFailedAssert in the current module scope.
# module-wide policy to change the failed assert # exception type in order to include a lineinfo onFailedAssert(msg): var e = new(TMyError) e.msg = msg e.lineinfo = instantiationInfo(-2) raise e
Source template `..^`(a, b: expr): expr
- a shortcut for '.. ^' to avoid the common gotcha that a space between '..' and '^' is required. Source
template `..<`(a, b: expr): expr
- a shortcut for '.. <' to avoid the common gotcha that a space between '..' and '<' is required. Source