system
nimony/lib/std/system.nim
System module for Nimony
type LongString = object fullLen: int64 rc: int64 capImpl: int64 data: UncheckedArray[char]
type string = object bytes: uint64 more: ptr LongString
func dollar`.bool(e: bool): stringtype enum = OrdinalEnum|HoleyEnumtype SomeSignedInt = int64|int8|int16|int32|int64type SomeUnsignedInt = uint64|uint8|uint16|uint32|uint64type SomeInteger = int64|int8|int16|int32|int64|uint64|uint8|uint16|uint32|uint64type SomeFloat = float64|float32|float64type SomeNumber = int64|int8|int16|int32|int64|uint64|uint8|uint16|uint32|uint64|float64|float32|float64type SomeOrdinal = int64|int8|int16|int32|int64|bool|OrdinalEnum|HoleyEnum|uint64|uint8|uint16|uint32|uint64template low(x: array[I, T]): Itemplate high(x: array[I, T]): Itype RootObj = objecttype RootRef = ref RootObjtemplate []=(x: T; i: int64; elem: typed)template []=(x: array[I, T]; i: I; elem: T)template []=(x: cstring; i: int64; elem: char)template []=(x: ptr UncheckedArray[T]; i: int64; elem: T)template []=(x: UncheckedArray[T]; i: int64; elem: T)template []=(x: ptr T; val: T)template []=(x: ref T; val: T)func inc(x: var T; y: V)func dec(x: var T; y: V)func inc(x: var T)func dec(x: var T)template +(x: int8): int8template +(x: int16): int16template +(x: int32): int32template +(x: int64): int64template +(x: float32): float32template +(x: float64): float64func +=(x: var T; y: T)func -=(x: var T; y: T)func *=(x: var T; y: T)template !=(x: untyped; y: untyped): untypedtemplate >=(x: untyped; y: untyped): untypedtemplate >(x: untyped; y: untyped): untypedtype Orderable = concept proc <=(x: Self, y: Self): bool
proc min(x: int8; y: int8): int8proc min(x: int16; y: int16): int16proc min(x: int32; y: int32): int32proc min(x: int64; y: int64): int64proc min(x: float32; y: float32): float32proc min(x: float64; y: float64): float64proc min(x: T; y: T): Tproc max(x: int8; y: int8): int8proc max(x: int16; y: int16): int16proc max(x: int32; y: int32): int32proc max(x: int64; y: int64): int64proc max(x: float32; y: float32): float32proc max(x: float64; y: float64): float64proc max(x: T; y: T): Ttype Comparable = concept func ==(x: Self, y: Self): bool func <(x: Self, y: Self): bool
func cmp(x: T; y: T): int64proc clamp(x: T; a: T; b: T): Tfunc $(x: uint64): stringfunc $(x: int64): stringfunc $(x: int32): stringfunc addInt(s: var string; x: int64)func addInt(s: var string; x: uint64)func $(b: bool): stringtype Stringable = concept func $(x: Self): string
template sizeof(_: T): int64Returns the size in bytes of the type of the given value.
func move(x: var T): TMoves
xout: returns its value and leavesxin a moved-from state.template len(x: typedesc[array[I, T]]): int64Returns the length of an array type. This is roughly the same as
high(T)-low(T)+1.template len(x: array[I, T]): int64Returns the length of an array. This is roughly the same as
high(T)-low(T)+1.func swap(x: var T; y: var T)Swaps two values bitwise without invoking
=sink,=copy, or=dup.template in(x: untyped; y: untyped): untypedtemplate notin(x: untyped; y: untyped): untypedtemplate isnot(x: untyped; y: untyped): untypediterator ..<(a: T; b: T): Titerator ..(a: T; b: T): Titerator >..(a: T; b: T): Titerator countdown(a: T; b: T; step: V): Titerator countup(a: T; b: T; step: int64): Ttype HasDefault = concept proc default(_: typedesc[Self]): Self
template default(x: typedesc[bool]): booltemplate default(x: typedesc[char]): chartemplate default(x: typedesc[int8]): int8template default(x: typedesc[uint8]): uint8template default(x: typedesc[int16]): int16template default(x: typedesc[uint16]): uint16template default(x: typedesc[int32]): int32template default(x: typedesc[uint32]): uint32template default(x: typedesc[int64]): int64template default(x: typedesc[uint64]): uint64template default(x: typedesc[float32]): float32template default(x: typedesc[float64]): float64template default(x: typedesc[string]): stringtemplate default(x: typedesc[T]): Ttemplate default(x: typedesc[T]): Ttemplate default(x: typedesc[T]): Ttemplate default(x: typedesc[T]): Ttemplate default(x: typedesc[pointer]): pointertemplate default(x: typedesc[cstring]): cstringfunc default(x: typedesc[array[I, T]]): array[I, T]template default(x: typedesc[set[T]]): set[T]func countBits32(x: uint32): int64func countBits64(x: uint64): int64template incl(x: var set[T]; y: set[T])template excl(x: var set[T]; y: set[T])iterator items(x: set[T]): Ttype BiggestInt = int64type BiggestFloat = float64type BiggestUInt = uint64type clong = int64type culong = uint64type cchar = chartype cschar = int8type cshort = int16type cint = int32type csize_t = uint64type clonglong = int64type cfloat = float32type cdouble = float64type clongdouble = float64type cuchar = chartype cushort = uint16type cuint = uint32type culonglong = uint64type cstringArray = ptr UncheckedArray[cstring]proc setExitFlush(p: proc () {.nimcall.})proc nimFlushStdStreams()proc cExit(code: int64)proc cAbort()type AtomMemModel = distinct int32var ATOMIC_RELAXED: AtomMemModelvar ATOMIC_CONSUME: AtomMemModelvar ATOMIC_ACQUIRE: AtomMemModelvar ATOMIC_RELEASE: AtomMemModelvar ATOMIC_ACQ_REL: AtomMemModelvar ATOMIC_SEQ_CST: AtomMemModelfunc atomicAddFetch(p: ptr T; val: T; mem: AtomMemModel): Tfunc atomicSubFetch(p: ptr T; val: T; mem: AtomMemModel): Tfunc atomicLoadN(p: ptr T; mem: AtomMemModel): Tfunc atomicStoreN(p: ptr T; val: T; mem: AtomMemModel)func atomicExchangeN(p: ptr T; val: T; mem: AtomMemModel): Tfunc atomicCompareExchangeN(p: ptr T; expected: ptr T; desired: T; weak: bool; succ: AtomMemModel; fail: AtomMemModel): boolfunc copyMem(dest: pointer; src: pointer; size: int64)func moveMem(dest: pointer; src: pointer; size: int64)func cmpMem(a: pointer; b: pointer; size: int64): int64func zeroMem(dest: pointer; size: int64)const vgTracking: boolproc vgRunningOnValgrind(): boolfunc alloc(size: int64): pointerfunc alloc0(size: int64): pointerfunc realloc(p: pointer; size: int64): pointerfunc dealloc(p: pointer)func allocatedSize(p: pointer): int64proc getOccupiedMem(): int64proc getFreeMem(): int64proc getTotalMem(): int64func allocFixed(size: int64): pointerfunc deallocFixed(p: pointer)proc continueAfterOutOfMem(size: int64)proc threadOutOfMem(): boolproc setOomHandler(handler: proc (size: int64) {.nimcall.})template linear()Marks an indexed accessor (
[]=, or avar T-returning[]) as linear: for distinct keys it yields distinct, non-aliasing, stable locations and never invalidates a previously obtained location.std/parfor's||uses this to allow parallelc[i] = …writes.seq/array indexing is linear;Tableindexing is not (it may rehash and relocate other slots).type seq = object len: int64 data: ptr UncheckedArray[T]
func =destroy(s: seq[T])func =wasMoved(s: var seq[T])func newSeq(size: int64): seq[T]func newSeqOf(size: int64; initValue: T): seq[T]func newSeqUninit(size: int64): seq[T]func newSeqOfCap(cap: int64): seq[T]template default(x: typedesc[seq[T]]): seq[T]func =dup(a: seq[T]): seq[T]func =copy(dest: var seq[T]; src: seq[T])func add(s: var seq[T]; elem: sink T)func len(s: seq[T]): int64func rawData(s: seq[T]): ptr UncheckedArray[T]func [](s: seq[T]; i: int64): var Tfunc []=(s: var seq[T]; i: int64; elem: sink T)func [](s: seq[T]; i: uint64): var Tfunc []=(s: var seq[T]; i: uint64; elem: sink T)func @(a: array[I, T]): seq[T]template @(a: array[0..-1, T]): seq[T]func del(s: var seq[T]; idx: int64)func addUnique(s: var seq[T]; x: sink T)func shrink(s: var seq[T]; newLen: int64)func growUnsafe(s: var seq[T]; newLen: int64)func grow(s: var seq[T]; newLen: int64; val: T)func setLen(s: var seq[T]; newLen: int64)proc newSeq(s: out seq[T]; newLen: int64)func high(s: seq[T]): int64func low(s: seq[T]): int64func pop(s: var seq[T]): Tfunc delete(s: var seq[T]; idx: int64)const OomBytes: uint64func len(s: string): int64func high(s: string): int64func low(s: string): int64func capacity(s: string): int64func isOom(s: string): boolfunc hashStr(s: string): uint64func readRawData(s: string; start: int64): ptr UncheckedArray[char]iterator items(s: string): chariterator pairs(s: string): tuple[int64, char]func =wasMoved(s: var string)func =destroy(s: string)func =copy(dest: var string; src: string)func =dup(s: string): stringfunc len(a: cstring): int64func readRawDataStable(s: var string; start: int64): ptr UncheckedArray[char]func prepareMutation(s: var string)func beginStore(s: var string; newLen: int64; start: int64): ptr UncheckedArray[char]func endStore(s: var string)func add(s: var string; c: char)func add(s: var string; part: string)func shrink(s: var string; newLen: int64)func setLen(s: var string; newLen: int64)func [](s: string; i: int64): charfunc []=(s: var string; i: int64; c: char)func substr(s: string; first: int64; last: int64): stringfunc substr(s: string; first: int64): stringfunc ==(a: string; b: string): boolfunc cmp(a: string; b: string): int64func <=(a: string; b: string): boolfunc <(a: string; b: string): boolfunc startsWithImpl(s: string; prefix: string): boolfunc newString(len: int64): stringfunc newStringOfCap(len: int64): stringfunc &(a: string; b: string): stringfunc &(x: string; y: char): stringfunc &(x: char; y: string): stringfunc &=(x: var string; y: string)func &=(x: var string; y: char)func terminatingZero(s: string): stringfunc borrowCStringUnsafe(s: cstring; l: int64): stringfunc borrowCStringUnsafe(s: cstring): stringfunc ensureTerminatingZero(s: var string)func toCString(s: var string): cstring not nilfunc fromCString(s: cstring): stringtemplate $(x: string): stringtype openArray = object a: ptr UncheckedArray[T] len: int64
func [](x: openArray[T]; idx: int64): var Tfunc []=(x: var openArray[T]; i: int64; elem: sink T)converter toOpenArray(x: array[I, T]): openArray[T]converter toOpenArray(s: seq[T]): openArray[T]converter toOpenArray(s: string): openArrayfunc high(a: openArray[T]): int64func low(a: openArray[T]): int64func len(a: openArray[T]): int64type Equatable = concept func ==(a: Self, b: Self): bool
func find(a: openArray[T]; elem: T): int64func contains(a: openArray[T]; elem: T): booliterator items(a: openArray[T]): var Titerator mitems(a: var openArray[T]): var Titerator pairs(a: openArray[T]): tuple[int64, var T]iterator mpairs(a: var openArray[T]): tuple[int64, var T]func ==(a: openArray[T]; b: openArray[T]): boolfunc toOpenArray(x: ptr UncheckedArray[T]; first: int64; last: int64): openArray[T]func toOpenArray(x: openArray[T]; first: int64; last: int64): openArray[T]proc @(a: openArray[T]): seq[T]type Hash = uint64type Hashable = concept func hash(a: Self): uint64
func !&(h: uint64; val: uint64): uint64func !$(h: uint64): uint64func hash(s: string): uint64func hash(u: uint64): uint64func hash(x: int64): uint64func hash(x: int32): uint64func hash(x: char): uint64func hash(x: bool): uint64func hash(x: float64): uint64func hash(x: float32): uint64func hash(x: T): uint64func hash(x: tuple[A, B]): uint64func hash(x: tuple[A, B, C]): uint64func hash(x: seq[T]): uint64func nextTry(h: uint64; maxHash: int64): uint64func hashIgnoreStyle(x: string): uint64func hashIgnoreStyle(sBuf: string; sPos: int64; ePos: int64): uint64func hashIgnoreCase(x: string): uint64func hashIgnoreCase(sBuf: string; sPos: int64; ePos: int64): uint64func arcInc(memLoc: var int64)func arcDec(memLoc: var int64): boolfunc arcIsUnique(memLoc: var int64): boolproc GC_ref(x: ref T)proc GC_unref(x: ref T)func new(x: out T)template runnableExamples(body: untyped)template ord(x: T): int64Returns the internal
intvalue ofx, including for enum with holes and distinct ordinal types.proc writeErr(s: string)proc writeErr(s: cstring)proc writeErr(x: int64)proc writeErr(x: uint64)proc panic(s: string)type Rtti = object dl: int64 dy: ptr UncheckedArray[uint32] mt: UncheckedArray[pointer]
func abs(x: T): TReturns the absolute value of
x.template isNil(s: cstring): boolfunc chr(u: 0..255): charConverts
uto achar, same aschar(u).func addFloat(result: var string; x: float64)func addFloat(result: var string; x: float32)func $(x: float64): stringfunc $(x: float32): stringtype ErrorCode = enum Success = (0, "Success") OverflowError = (1, "OverflowError") Failure = (2, "Failure") BugError = (3, "BugError") IndexError = (4, "IndexError") RangeError = (5, "RangeError") OverlapError = (6, "OverlapError") SyntaxError = (7, "SyntaxError") OutOfMemError = (8, "OutOfMemError") DiskFullError = (9, "DiskFullError") StackOverflow = (10, "StackOverflow") IOError = (11, "IOError") ValueError = (12, "ValueError") KeyError = (13, "KeyError") EndOfStreamError = (14, "EndOfStreamError") SkipError = (15, "SkipError") FullError = (16, "FullError") EmptyError = (17, "EmptyError") BusyError = (18, "BusyError") DeadResource = (19, "DeadResource") ResourceExhaustedError = (20, "ResourceExhaustedError") DescriptorExhaustedError = (21, "DescriptorExhaustedError") PermissionDenied = (22, "PermissionDenied") RetryError = (23, "RetryError") TimeoutError = (24, "TimeoutError") InterruptedError = (25, "InterruptedError") DeadlockError = (26, "DeadlockError") LockedError = (27, "LockedError") FormatMismatch = (28, "FormatMismatch") AlreadyConnected = (29, "AlreadyConnected") AddressNotAvailable = (30, "AddressNotAvailable") AddressFamilyUnsupported = (31, "AddressFamilyUnsupported") BadOperation = (32, "BadOperation") AbortedOperation = (33, "AbortedOperation") UnimplementedOperation = (34, "UnimplementedOperation") AlreadyInProgress = (35, "AlreadyInProgress") NameTooLong = (36, "NameTooLong") NameExists = (37, "NameExists") NameNotFound = (38, "NameNotFound") ContentTooLong = (39, "ContentTooLong") BadDescriptor = (40, "BadDescriptor") BadExecutable = (41, "BadExecutable") BadLink = (42, "BadLink") BadProtocol = (43, "BadProtocol") ProtocolError = (44, "ProtocolError") ReadonlyProtection = (45, "ReadonlyProtection") SegFault = (46, "SegFault") DiskCorruption = (47, "DiskCorruption") Disconnected = (48, "Disconnected") RefusedConnection = (49, "RefusedConnection") UnreachableHost = (50, "UnreachableHost") UnrecoverableState = (51, "UnrecoverableState") AuthenticationRequired = (52, "AuthenticationRequired") RedirectError = (53, "RedirectError") Reserved1 = (54, "Reserved1") Reserved2 = (55, "Reserved2") Reserved3 = (56, "Reserved3") Reserved4 = (57, "Reserved4") Reserved5 = (58, "Reserved5") Reserved6 = (59, "Reserved6") Reserved7 = (60, "Reserved7") Reserved8 = (61, "Reserved8") Reserved9 = (62, "Reserved9")
func dollar`.ErrorCode(e: ErrorCode): stringvar localErr: ErrorCodetype ContinuationProc = proc (coro: ptr CoroutineBase): Continuation {.nimcall.}type Continuation = object fn: proc (coro: ptr CoroutineBase): Continuation {.nimcall.} env: ptr CoroutineBase
type CoroutineBase = object caller: Continuation callee: ptr CoroutineBase
method cancel(coro: ptr CoroutineBase)type Scheduler = proc (c: Continuation): Continuation {.nimcall.}A scheduler is a function that takes a continuation and returns a new continuation.
proc setScheduler(handler: proc (c: Continuation): Continuation {.nimcall.})proc advance(c: Continuation): ContinuationSingle steps through a list of continuations. Usually this does not need to be called directly. Used by the compiler to run a coroutine.
proc complete(c: Continuation)Used by the compiler to run a coroutine until it has no next step (
stopping): it either finishes or parks (delay(); suspend()) to await an external scheduler. With the default trivial scheduler a park simply stops the loop; a real scheduler resumes parked continuations and drives them onward. Takescby value so a coroutine may reassign the variable it was driven from (e.g. to reschedule viadelay(call)). Baresuspend()transitions synchronously, so it does not stop the loop.proc parked(c: Continuation): boolTrue when a coroutine has parked via
suspend()and not yet been resumed. Theenvfield identifies the coroutine frame.proc stopping(c: Continuation): boolTrue when a coroutine has no next step: either finished or parked.
proc finished(c: Continuation): boolTrue once a coroutine has run to completion. Compatible with Nim's
finishedbuiltin: returnstruewhen there are no more values to produce. Used by the closure-iterator trampoline that the compiler emits forfor x in closureIter(...)loops.Parked continuations (
suspend) are not finished: they havefn == nilbut a non-nilenv.proc finalizeCoroutine(c: var Continuation)Cancels and deallocates a coroutine frame that is still live (i.e. the loop exited via
break/return/exception before the iterator completed, or the coroutine is parked). A no-op once the coroutine has run to completion since its terminating state already freed the frame. Called from thefinallyclause of the closure-iterator trampoline.For iter-VALUE-owned frames (the iter-value tuple's env slot owns the frame as a
ref CoroType), we runcancelbut skipdeallocFrame— the ref's destructor frees the memory later when the iter-value goes out of scope. The ownership marker isframe.caller.env: nil ⇒ wrapper-allocated, non-nil ⇒ value-owned.func ==(x: T; y: T): boolReturn true only if each fields of
xandyare equal.func ==(x: seq[T]; y: seq[T]): boolGeneric equals operator for sequences: relies on a equals operator for the element type
T.func addEscapedChar(s: var string; c: char)Adds a char to string
sand applies the following escaping:- replaces any
\by\\ - replaces any
'by\' - replaces any
"by\" - replaces any
\aby\\a - replaces any
\bby\\b - replaces any
\tby\\t - replaces any
\nby\\n - replaces any
\vby\\v - replaces any
\fby\\f - replaces any
\rby\\r - replaces any
\eby\\e - replaces any other character not in the set
{\21..\126}
by
\xHHwhereHHis its hexadecimal valueThe procedure has been designed so that its output is usable for many different common syntaxes.
.. warning:: This is not correct for producing ANSI C code!
- replaces any
func addQuoted(s: var string; x: T)Appends
xto stringsin place, applying quoting and escaping ifxis a string or char.See addEscapedChar for the escaping scheme. When
xis a string, characters in the range{\128..\255}are never escaped so that multibyte UTF-8 characters are untouched (note that this behavior is different fromaddEscapedChar).The Nim standard library uses this function on the elements of collections when producing a string representation of a collection. It is recommended to use this function as well for user-side collections. Users may overload
addQuotedfor custom (string-like) types if they want to implement a customized element representation.nim var tmp = "" tmp.addQuoted(1) tmp.add(", ") tmp.addQuoted("string") tmp.add(", ") tmp.addQuoted('c') assert(tmp == """1, "string", 'c'""")type Natural = int64is an
inttype ranging from zero to the maximum value of anint. This type is often useful for documentation and debugging.type Positive = int64is an
inttype ranging from one to the maximum value of anint. This type is often useful for documentation and debugging.type HSlice = object a: T b: U
type Slice = HSlice[T,T]An alias for
HSlice[T, T].func ..(a: sink T; b: sink U): HSlice[T,U]Binary
slice:idx: operator that constructs an interval[a, b], bothaandbare inclusive.Slices can also be used in the set constructor and in ordinal case statements, but then they are special-cased by the compiler.
nim let a = [10, 20, 30, 40, 50] echo a[2 .. 3] # @[30, 40]func ..<(a: sink T; b: sink U): HSlice[T,U]Binary
..<operator that constructs the half-open interval[a, b), i.e. it is equivalent toa .. pred(b).This is the value form used by slice indexing such as
s[a ..< b]; the for-loop formfor i in a ..< bresolves to the..<iterator.func contains(s: HSlice[T,T]; x: T): boolTrue when
xlies within the inclusive intervals; enablesx in a .. b.type BackwardsIndex = distinct int64Type constructed by
^for reversed array/string/seq access.template ^(x: int64): BackwardsIndexBuiltin
roof:idx: operator.a[^x]is a shortcut fora[a.len - x].template [](s: seq[T]; i: BackwardsIndex): var Ttemplate [](s: openArray[T]; i: BackwardsIndex): var Ttemplate [](s: string; i: BackwardsIndex): var chartemplate ..^(a: untyped; b: untyped): untypedA shortcut for
a .. ^b. Note thata .. ^bwould be tokenized asa..^banyway, so this operator must exist for that to parse.func [](s: string; x: HSlice): stringSlice indexing: returns the substring for the inclusive range
x.a .. x.b(a fresh copy). Works withs[a .. b]ands[a ..< b].func [](s: string; x: HSlice): stringSlice indexing with a backwards upper bound, e.g.
s[a .. ^1].func [](s: seq[T]; x: HSlice): seq[T]Slice indexing: returns a fresh
seqwith copies of the elements in the inclusive rangex.a .. x.b. Works withs[a .. b]ands[a ..< b].func [](s: seq[T]; x: HSlice): seq[T]Slice indexing with a backwards upper bound, e.g.
s[a .. ^1].type TypeOfMode = enum typeOfProc = (0, "typeOfProc") typeOfIter = (1, "typeOfIter")
func dollar`.TypeOfMode(e: TypeOfMode): stringproc allocFrame(size: int64): ptr CoroutineBaseAllocates a new coroutine frame of the given size on the heap.
ZEROED, and that is load-bearing rather than tidy. A frame holds the coroutine's locals, and the CPS lowering writes them with ordinary DESTRUCTIVE assignments —
=destroythe old value, then store the new one — including the very first write, when there is no old value. On rawallocmemory that first=destroyreads whatever the allocator last left there: for astringit isnimStrDestroybranching on a garbageslen, and a garbageslen > 14would calldeallocon a garbage pointer.Zero is a valid — and destructible — initial value for every type that can live in a frame: a
stringreadsslen = 0(the empty short string), aseqreadsdata = nil, arefreads nil, and=destroyon each is a no-op.deallocFramebelow also readsframe.calleebefore anything is guaranteed to have written it.The alternative — teaching the lowering to emit an initializing store for the first write to each frame field — is better code, and is not a prerequisite for this being correct: it would make the memset redundant, not necessary.
proc deallocFrame(frame: ptr CoroutineBase)Frees a coroutine frame previously allocated by
allocFrame.type Exception = object msg: string
var exc: ref Exceptionproc newException(exceptn: typedesc[T]; message: string): ref TCreates a heap-based exception object of type
Tfor Nim 2 interop:raise newException(ValueError, "wrong value").