styleCheck: make the compiler and large parts of the stdlib compatible with --styleCheck:error

This commit is contained in:
Araq 2019-07-10 12:42:23 +02:00
commit c94647aeca
90 changed files with 680 additions and 652 deletions

View file

@ -499,7 +499,7 @@ type
filename*: string
line*,column*: int
proc `$`*(arg: Lineinfo): string =
proc `$`*(arg: LineInfo): string =
# BUG: without `result = `, gives compile error
result = arg.filename & "(" & $arg.line & ", " & $arg.column & ")"
@ -988,16 +988,16 @@ proc newBlockStmt*(label, body: NimNode): NimNode {.compileTime.} =
## Create a new block statement with label
return newNimNode(nnkBlockStmt).add(label, body)
proc newBlockStmt*(body: NimNode): NimNode {.compiletime.} =
proc newBlockStmt*(body: NimNode): NimNode {.compileTime.} =
## Create a new block: stmt
return newNimNode(nnkBlockStmt).add(newEmptyNode(), body)
proc newVarStmt*(name, value: NimNode): NimNode {.compiletime.} =
proc newVarStmt*(name, value: NimNode): NimNode {.compileTime.} =
## Create a new var stmt
return newNimNode(nnkVarSection).add(
newNimNode(nnkIdentDefs).add(name, newNimNode(nnkEmpty), value))
proc newLetStmt*(name, value: NimNode): NimNode {.compiletime.} =
proc newLetStmt*(name, value: NimNode): NimNode {.compileTime.} =
## Create a new let stmt
return newNimNode(nnkLetSection).add(
newNimNode(nnkIdentDefs).add(name, newNimNode(nnkEmpty), value))
@ -1095,7 +1095,7 @@ proc newProc*(name = newEmptyNode();
body)
proc newIfStmt*(branches: varargs[tuple[cond, body: NimNode]]):
NimNode {.compiletime.} =
NimNode {.compileTime.} =
## Constructor for ``if`` statements.
##
## .. code-block:: nim
@ -1233,7 +1233,7 @@ proc `body=`*(someProc: NimNode, val: NimNode) {.compileTime.} =
else:
badNodeKind someProc, "body="
proc basename*(a: NimNode): NimNode {.compiletime, benign.}
proc basename*(a: NimNode): NimNode {.compileTime, benign.}
proc `$`*(node: NimNode): string {.compileTime.} =
## Get the string of an identifier node
@ -1396,7 +1396,7 @@ else:
else:
result = false
proc hasArgOfName*(params: NimNode; name: string): bool {.compiletime.}=
proc hasArgOfName*(params: NimNode; name: string): bool {.compileTime.}=
## Search nnkFormalParams for an argument.
expectKind(params, nnkFormalParams)
for i in 1 ..< params.len:
@ -1404,7 +1404,7 @@ proc hasArgOfName*(params: NimNode; name: string): bool {.compiletime.}=
if name.eqIdent( $ node[0]):
return true
proc addIdentIfAbsent*(dest: NimNode, ident: string) {.compiletime.} =
proc addIdentIfAbsent*(dest: NimNode, ident: string) {.compileTime.} =
## Add ident to dest if it is not present. This is intended for use
## with pragmas.
for node in dest.children:

View file

@ -170,14 +170,14 @@ proc add*[T](x: var seq[T]; value: sink T) {.magic: "AppendSeqElem", noSideEffec
proc setLen[T](s: var seq[T], newlen: Natural) =
{.noSideEffect.}:
if newlen < s.len:
shrink(s, newLen)
shrink(s, newlen)
else:
let oldLen = s.len
if newLen <= oldLen: return
if newlen <= oldLen: return
var xu = cast[ptr NimSeqV2[T]](addr s)
if xu.p == nil or xu.p.cap < newLen:
xu.p = cast[typeof(xu.p)](prepareSeqAdd(oldLen, xu.p, newLen - oldLen, sizeof(T)))
xu.len = newLen
if xu.p == nil or xu.p.cap < newlen:
xu.p = cast[typeof(xu.p)](prepareSeqAdd(oldLen, xu.p, newlen - oldLen, sizeof(T)))
xu.len = newlen
when false:
proc resize[T](s: var NimSeqV2[T]) =

View file

@ -12,12 +12,12 @@
when false:
# these are to be implemented or changed in the code generator.
#proc rawNewStringNoInit(space: int): NimString {.compilerProc.}
#proc rawNewStringNoInit(space: int): NimString {.compilerproc.}
# seems to be unused.
proc copyDeepString(src: NimString): NimString {.inline.}
# ----------------- sequences ----------------------------------------------
proc incrSeqV3(s: PGenericSeq, typ: PNimType): PGenericSeq {.compilerProc.}
proc incrSeqV3(s: PGenericSeq, typ: PNimType): PGenericSeq {.compilerproc.}
proc setLengthSeqV2(s: PGenericSeq, typ: PNimType, newLen: int): PGenericSeq {.
compilerRtl.}
proc newSeq(typ: PNimType, len: int): pointer {.compilerRtl.}
@ -109,7 +109,7 @@ proc nimAddCharV1(s: var NimStringV2; c: char) {.compilerRtl.} =
s.p.data[s.len+1] = '\0'
inc s.len
proc toNimStr(str: cstring, len: int): NimStringV2 {.compilerProc.} =
proc toNimStr(str: cstring, len: int): NimStringV2 {.compilerproc.} =
if len <= 0:
result = NimStringV2(len: 0, p: nil)
else:
@ -126,7 +126,7 @@ proc cstrToNimstr(str: cstring): NimStringV2 {.compilerRtl.} =
if str == nil: toNimStr(str, 0)
else: toNimStr(str, str.len)
proc nimToCStringConv(s: NimStringV2): cstring {.compilerProc, nonReloadable, inline.} =
proc nimToCStringConv(s: NimStringV2): cstring {.compilerproc, nonReloadable, inline.} =
if s.len == 0: result = cstring""
else: result = cstring(unsafeAddr s.p.data)
@ -141,7 +141,7 @@ proc appendChar(dest: var NimStringV2; c: char) {.compilerproc, inline.} =
dest.p.data[dest.len+1] = '\0'
inc dest.len
proc rawNewString(space: int): NimStringV2 {.compilerProc.} =
proc rawNewString(space: int): NimStringV2 {.compilerproc.} =
# this is also 'system.newStringOfCap'.
if space <= 0:
result = NimStringV2(len: 0, p: nil)
@ -152,7 +152,7 @@ proc rawNewString(space: int): NimStringV2 {.compilerProc.} =
p.cap = space
result = NimStringV2(len: 0, p: p)
proc mnewString(len: int): NimStringV2 {.compilerProc.} =
proc mnewString(len: int): NimStringV2 {.compilerproc.} =
if len <= 0:
result = NimStringV2(len: 0, p: nil)
else:

View file

@ -865,7 +865,7 @@ proc yamlNextToken(g: var GeneralTokenizer) =
inc(pos)
while g.buf[pos] in {'0'..'9', '+', '-'}: inc(pos)
of '0'..'9': yamlPossibleNumber(g, pos)
of '\0': g.kind = gtEOF
of '\0': g.kind = gtEof
else: yamlPlainStrLit(g, pos)
else:
# outside document
@ -883,7 +883,7 @@ proc yamlNextToken(g: var GeneralTokenizer) =
of '#':
g.kind = gtComment
while g.buf[pos] notin {'\0', '\x0A', '\x0D'}: inc(pos)
of '\0': g.kind = gtEOF
of '\0': g.kind = gtEof
else:
g.kind = gtNone
g.state = gtOther

View file

@ -32,6 +32,9 @@
# error only if they actualy try to use the missing declaration
{.deadCodeElim: on.} # dce option deprecated
when defined(nimHasStyleChecks):
{.push styleChecks: off.}
# TODO these constants don't seem to be fetched from a header file for unknown
# platforms - where do they come from and why are they here?
when false:
@ -114,13 +117,13 @@ when StatHasNanoseconds:
## Second-granularity time of last status change.
result = s.st_ctim.tv_sec
else:
proc st_atim*(s: Stat): TimeSpec {.inline.} =
proc st_atim*(s: Stat): Timespec {.inline.} =
## Nanosecond-granularity time of last access.
result.tv_sec = s.st_atime
proc st_mtim*(s: Stat): TimeSpec {.inline.} =
proc st_mtim*(s: Stat): Timespec {.inline.} =
## Nanosecond-granularity time of last data modification.
result.tv_sec = s.st_mtime
proc st_ctim*(s: Stat): TimeSpec {.inline.} =
proc st_ctim*(s: Stat): Timespec {.inline.} =
## Nanosecond-granularity time of last data modification.
result.tv_sec = s.st_ctime
@ -269,45 +272,45 @@ proc strerror*(errnum: cint): cstring {.importc, header: "<string.h>".}
proc pthread_atfork*(a1, a2, a3: proc () {.noconv.}): cint {.
importc, header: "<pthread.h>".}
proc pthread_attr_destroy*(a1: ptr PthreadAttr): cint {.
proc pthread_attr_destroy*(a1: ptr Pthread_attr): cint {.
importc, header: "<pthread.h>".}
proc pthread_attr_getdetachstate*(a1: ptr PthreadAttr, a2: cint): cint {.
proc pthread_attr_getdetachstate*(a1: ptr Pthread_attr, a2: cint): cint {.
importc, header: "<pthread.h>".}
proc pthread_attr_getguardsize*(a1: ptr PthreadAttr, a2: var cint): cint {.
proc pthread_attr_getguardsize*(a1: ptr Pthread_attr, a2: var cint): cint {.
importc, header: "<pthread.h>".}
proc pthread_attr_getinheritsched*(a1: ptr PthreadAttr,
proc pthread_attr_getinheritsched*(a1: ptr Pthread_attr,
a2: var cint): cint {.importc, header: "<pthread.h>".}
proc pthread_attr_getschedparam*(a1: ptr PthreadAttr,
proc pthread_attr_getschedparam*(a1: ptr Pthread_attr,
a2: ptr Sched_param): cint {.importc, header: "<pthread.h>".}
proc pthread_attr_getschedpolicy*(a1: ptr PthreadAttr,
proc pthread_attr_getschedpolicy*(a1: ptr Pthread_attr,
a2: var cint): cint {.importc, header: "<pthread.h>".}
proc pthread_attr_getscope*(a1: ptr PthreadAttr,
proc pthread_attr_getscope*(a1: ptr Pthread_attr,
a2: var cint): cint {.importc, header: "<pthread.h>".}
proc pthread_attr_getstack*(a1: ptr PthreadAttr,
proc pthread_attr_getstack*(a1: ptr Pthread_attr,
a2: var pointer, a3: var int): cint {.importc, header: "<pthread.h>".}
proc pthread_attr_getstackaddr*(a1: ptr PthreadAttr,
proc pthread_attr_getstackaddr*(a1: ptr Pthread_attr,
a2: var pointer): cint {.importc, header: "<pthread.h>".}
proc pthread_attr_getstacksize*(a1: ptr PthreadAttr,
proc pthread_attr_getstacksize*(a1: ptr Pthread_attr,
a2: var int): cint {.importc, header: "<pthread.h>".}
proc pthread_attr_init*(a1: ptr PthreadAttr): cint {.
proc pthread_attr_init*(a1: ptr Pthread_attr): cint {.
importc, header: "<pthread.h>".}
proc pthread_attr_setdetachstate*(a1: ptr PthreadAttr, a2: cint): cint {.
proc pthread_attr_setdetachstate*(a1: ptr Pthread_attr, a2: cint): cint {.
importc, header: "<pthread.h>".}
proc pthread_attr_setguardsize*(a1: ptr PthreadAttr, a2: int): cint {.
proc pthread_attr_setguardsize*(a1: ptr Pthread_attr, a2: int): cint {.
importc, header: "<pthread.h>".}
proc pthread_attr_setinheritsched*(a1: ptr PthreadAttr, a2: cint): cint {.
proc pthread_attr_setinheritsched*(a1: ptr Pthread_attr, a2: cint): cint {.
importc, header: "<pthread.h>".}
proc pthread_attr_setschedparam*(a1: ptr PthreadAttr,
proc pthread_attr_setschedparam*(a1: ptr Pthread_attr,
a2: ptr Sched_param): cint {.importc, header: "<pthread.h>".}
proc pthread_attr_setschedpolicy*(a1: ptr PthreadAttr, a2: cint): cint {.
proc pthread_attr_setschedpolicy*(a1: ptr Pthread_attr, a2: cint): cint {.
importc, header: "<pthread.h>".}
proc pthread_attr_setscope*(a1: ptr PthreadAttr, a2: cint): cint {.importc,
proc pthread_attr_setscope*(a1: ptr Pthread_attr, a2: cint): cint {.importc,
header: "<pthread.h>".}
proc pthread_attr_setstack*(a1: ptr PthreadAttr, a2: pointer, a3: int): cint {.
proc pthread_attr_setstack*(a1: ptr Pthread_attr, a2: pointer, a3: int): cint {.
importc, header: "<pthread.h>".}
proc pthread_attr_setstackaddr*(a1: ptr PthreadAttr, a2: pointer): cint {.
proc pthread_attr_setstackaddr*(a1: ptr Pthread_attr, a2: pointer): cint {.
importc, header: "<pthread.h>".}
proc pthread_attr_setstacksize*(a1: ptr PthreadAttr, a2: int): cint {.
proc pthread_attr_setstacksize*(a1: ptr Pthread_attr, a2: int): cint {.
importc, header: "<pthread.h>".}
proc pthread_barrier_destroy*(a1: ptr Pthread_barrier): cint {.
importc, header: "<pthread.h>".}
@ -350,7 +353,7 @@ proc pthread_condattr_init*(a1: ptr Pthread_condattr): cint {.importc, header: "
proc pthread_condattr_setclock*(a1: ptr Pthread_condattr,a2: ClockId): cint {.importc, header: "<pthread.h>".}
proc pthread_condattr_setpshared*(a1: ptr Pthread_condattr, a2: cint): cint {.importc, header: "<pthread.h>".}
proc pthread_create*(a1: ptr Pthread, a2: ptr PthreadAttr,
proc pthread_create*(a1: ptr Pthread, a2: ptr Pthread_attr,
a3: proc (x: pointer): pointer {.noconv.}, a4: pointer): cint {.importc, header: "<pthread.h>".}
proc pthread_detach*(a1: Pthread): cint {.importc, header: "<pthread.h>".}
proc pthread_equal*(a1, a2: Pthread): cint {.importc, header: "<pthread.h>".}
@ -1068,3 +1071,6 @@ proc setrlimit*(resource: cint, rlp: var RLimit): cint
proc getrlimit*(resource: cint, rlp: var RLimit): cint
{.importc: "getrlimit",header: "<sys/resource.h>".}
## The getrlimit() system call gets resource limits.
when defined(nimHasStyleChecks):
{.pop.} # {.push styleChecks: off.}

View file

@ -19,7 +19,10 @@ const
# On Linux:
# timer_{create,delete,settime,gettime},
# clock_{getcpuclockid, getres, gettime, nanosleep, settime} lives in librt
{.passL: "-lrt".}
{.passl: "-lrt".}
when defined(nimHasStyleChecks):
{.push styleChecks: off.}
# Types
@ -32,7 +35,7 @@ type
SocketHandle* = distinct cint # The type used to represent socket descriptors
# not detected by detect.nim, guarded by #ifdef __USE_UNIX98 in glibc
const SIG_HOLD* = cast[SigHandler](2)
const SIG_HOLD* = cast[Sighandler](2)
type
Time* {.importc: "time_t", header: "<time.h>".} = distinct clong
@ -296,7 +299,7 @@ type
sigev_signo*: cint ## Signal number.
sigev_notify*: cint ## Notification type.
sigev_notify_function*: proc (x: SigVal) {.noconv.} ## Notification func.
sigev_notify_attributes*: ptr PthreadAttr ## Notification attributes.
sigev_notify_attributes*: ptr Pthread_attr ## Notification attributes.
abi: array[12, int]
SigVal* {.importc: "union sigval",
@ -579,4 +582,7 @@ proc WSTOPSIG*(s:cint): cint = WEXITSTATUS(s)
proc WIFEXITED*(s:cint) : bool = WTERMSIG(s) == 0
proc WIFSIGNALED*(s:cint) : bool = (cast[int8]((s and 0x7f) + 1) shr 1) > 0
proc WIFSTOPPED*(s:cint) : bool = (s and 0xff) == 0x7f
proc WIFCONTINUED*(s:cint) : bool = s == W_CONTINUED
proc WIFCONTINUED*(s:cint) : bool = s == WCONTINUED
when defined(nimHasStyleChecks):
{.pop.} # {.push styleChecks: off.}

View file

@ -9,6 +9,9 @@
{.deadCodeElim: on.} # dce option deprecated
when defined(nimHasStyleChecks):
{.push styleChecks: off.}
const
hasSpawnH = true # should exist for every Posix system nowadays
hasAioH = false
@ -272,7 +275,7 @@ type
sigev_signo*: cint ## Signal number.
sigev_value*: SigVal ## Signal value.
sigev_notify_function*: proc (x: SigVal) {.noconv.} ## Notification func.
sigev_notify_attributes*: ptr PthreadAttr ## Notification attributes.
sigev_notify_attributes*: ptr Pthread_attr ## Notification attributes.
SigVal* {.importc: "union sigval",
header: "<signal.h>", final, pure.} = object ## struct sigval
@ -594,3 +597,6 @@ proc WIFSTOPPED*(s: cint): bool {.importc, header: "<sys/wait.h>".}
## True if child is currently stopped.
proc WIFCONTINUED*(s: cint): bool {.importc, header: "<sys/wait.h>".}
## True if child has been continued.
when defined(nimHasStyleChecks):
{.pop.}

View file

@ -9,6 +9,9 @@
{.deadCodeElim: on.} # dce option deprecated
when defined(nimHasStyleChecks):
{.push styleChecks: off.}
const
hasSpawnH = true # should exist for every Posix system nowadays
hasAioH = defined(linux)
@ -281,7 +284,7 @@ type
sigev_signo*: cint ## Signal number.
sigev_value*: SigVal ## Signal value.
sigev_notify_function*: proc (x: SigVal) {.noconv.} ## Notification func.
sigev_notify_attributes*: ptr PthreadAttr ## Notification attributes.
sigev_notify_attributes*: ptr Pthread_attr ## Notification attributes.
SigVal* {.importc: "union sigval",
header: "<signal.h>", final, pure.} = object ## struct sigval
@ -603,3 +606,6 @@ proc WIFSTOPPED*(s: cint): bool {.importc, header: "<sys/wait.h>".}
## True if child is currently stopped.
proc WIFCONTINUED*(s: cint): bool {.importc, header: "<sys/wait.h>".}
## True if child has been continued.
when defined(nimHasStyleChecks):
{.pop.}

View file

@ -532,7 +532,7 @@ func isSorted*[T](a: openArray[T],
if cmp(a[i],a[i+1]) * order > 0:
return false
proc isSorted*[T](a: openarray[T], order = SortOrder.Ascending): bool =
proc isSorted*[T](a: openArray[T], order = SortOrder.Ascending): bool =
## Shortcut version of ``isSorted`` that uses ``system.cmp[T]`` as the comparison function.
##
## **See also:**
@ -588,7 +588,7 @@ proc product*[T](x: openArray[seq[T]]): seq[seq[T]] =
index = 0
indexes[index] -= 1
proc nextPermutation*[T](x: var openarray[T]): bool {.discardable.} =
proc nextPermutation*[T](x: var openArray[T]): bool {.discardable.} =
## Calculates the next lexicographic permutation, directly modifying ``x``.
## The result is whether a permutation happened, otherwise we have reached
## the last-ordered permutation.
@ -628,7 +628,7 @@ proc nextPermutation*[T](x: var openarray[T]): bool {.discardable.} =
result = true
proc prevPermutation*[T](x: var openarray[T]): bool {.discardable.} =
proc prevPermutation*[T](x: var openArray[T]): bool {.discardable.} =
## Calculates the previous lexicographic permutation, directly modifying
## ``x``. The result is whether a permutation happened, otherwise we have
## reached the first-ordered permutation.
@ -693,7 +693,7 @@ when isMainModule:
assert arr1.reversed(i, high(arr1)) == arr1.reversed()[0 .. high(arr1) - i]
proc rotateInternal[T](arg: var openarray[T]; first, middle, last: int): int =
proc rotateInternal[T](arg: var openArray[T]; first, middle, last: int): int =
## A port of std::rotate from c++. Ported from `this reference <http://www.cplusplus.com/reference/algorithm/rotate/>`_.
result = first + last - middle
@ -732,20 +732,20 @@ proc rotateInternal[T](arg: var openarray[T]; first, middle, last: int): int =
elif next == last:
next = mMiddle
proc rotatedInternal[T](arg: openarray[T]; first, middle, last: int): seq[T] =
proc rotatedInternal[T](arg: openArray[T]; first, middle, last: int): seq[T] =
result = newSeq[T](arg.len)
for i in 0 ..< first:
result[i] = arg[i]
let N = last - middle
let M = middle - first
for i in 0 ..< N:
let n = last - middle
let m = middle - first
for i in 0 ..< n:
result[first+i] = arg[middle+i]
for i in 0 ..< M:
result[first+N+i] = arg[first+i]
for i in 0 ..< m:
result[first+n+i] = arg[first+i]
for i in last ..< arg.len:
result[i] = arg[i]
proc rotateLeft*[T](arg: var openarray[T]; slice: HSlice[int, int]; dist: int): int {.discardable.} =
proc rotateLeft*[T](arg: var openArray[T]; slice: HSlice[int, int]; dist: int): int {.discardable.} =
## Performs a left rotation on a range of elements. If you want to rotate
## right, use a negative ``dist``. Specifically, ``rotateLeft`` rotates
## the elements at ``slice`` by ``dist`` positions.
@ -782,7 +782,7 @@ proc rotateLeft*[T](arg: var openarray[T]; slice: HSlice[int, int]; dist: int):
let distLeft = ((dist mod sliceLen) + sliceLen) mod sliceLen
arg.rotateInternal(slice.a, slice.a+distLeft, slice.b + 1)
proc rotateLeft*[T](arg: var openarray[T]; dist: int): int {.discardable.} =
proc rotateLeft*[T](arg: var openArray[T]; dist: int): int {.discardable.} =
## Default arguments for slice, so that this procedure operates on the entire
## ``arg``, and not just on a part of it.
##
@ -801,7 +801,7 @@ proc rotateLeft*[T](arg: var openarray[T]; dist: int): int {.discardable.} =
let distLeft = ((dist mod arglen) + arglen) mod arglen
arg.rotateInternal(0, distLeft, arglen)
proc rotatedLeft*[T](arg: openarray[T]; slice: HSlice[int, int], dist: int): seq[T] =
proc rotatedLeft*[T](arg: openArray[T]; slice: HSlice[int, int], dist: int): seq[T] =
## Same as ``rotateLeft``, just with the difference that it does
## not modify the argument. It creates a new ``seq`` instead.
##
@ -830,7 +830,7 @@ proc rotatedLeft*[T](arg: openarray[T]; slice: HSlice[int, int], dist: int): seq
let distLeft = ((dist mod sliceLen) + sliceLen) mod sliceLen
arg.rotatedInternal(slice.a, slice.a+distLeft, slice.b+1)
proc rotatedLeft*[T](arg: openarray[T]; dist: int): seq[T] =
proc rotatedLeft*[T](arg: openArray[T]; dist: int): seq[T] =
## Same as ``rotateLeft``, just with the difference that it does
## not modify the argument. It creates a new ``seq`` instead.
##

View file

@ -232,7 +232,7 @@ when defined(windows) or defined(nimdoc):
CompletionData* = object
fd*: AsyncFD # TODO: Rename this.
cb*: owned(proc (fd: AsyncFD, bytesTransferred: Dword,
cb*: owned(proc (fd: AsyncFD, bytesTransferred: DWORD,
errcode: OSErrorCode) {.closure, gcsafe.})
cell*: ForeignCell # we need this `cell` to protect our `cb` environment,
# when using RegisterWaitForSingleObject, because
@ -328,7 +328,7 @@ when defined(windows) or defined(nimdoc):
if at == -1: winlean.INFINITE
else: at.int32
var lpNumberOfBytesTransferred: Dword
var lpNumberOfBytesTransferred: DWORD
var lpCompletionKey: ULONG_PTR
var customOverlapped: PCustomOverlapped
let res = getQueuedCompletionStatus(p.ioPort,
@ -379,10 +379,10 @@ when defined(windows) or defined(nimdoc):
proc initPointer(s: SocketHandle, fun: var pointer, guid: var GUID): bool =
# Ref: https://github.com/powdahound/twisted/blob/master/twisted/internet/iocpreactor/iocpsupport/winsock_pointers.c
var bytesRet: Dword
var bytesRet: DWORD
fun = nil
result = WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER, addr guid,
sizeof(GUID).Dword, addr fun, sizeof(pointer).Dword,
sizeof(GUID).DWORD, addr fun, sizeof(pointer).DWORD,
addr bytesRet, nil, nil) == 0
proc initAll() =
@ -425,12 +425,12 @@ when defined(windows) or defined(nimdoc):
dataBuf.buf = cast[cstring](alloc0(size))
dataBuf.len = size.ULONG
var bytesReceived: Dword
var flagsio = flags.toOSFlags().Dword
var bytesReceived: DWORD
var flagsio = flags.toOSFlags().DWORD
var ol = PCustomOverlapped()
GC_ref(ol)
ol.data = CompletionData(fd: socket, cb:
proc (fd: AsyncFD, bytesCount: Dword, errcode: OSErrorCode) =
proc (fd: AsyncFD, bytesCount: DWORD, errcode: OSErrorCode) =
if not retFuture.finished:
if errcode == OSErrorCode(-1):
if bytesCount == 0 and dataBuf.buf[0] == '\0':
@ -502,12 +502,12 @@ when defined(windows) or defined(nimdoc):
dataBuf.buf = cast[cstring](buf)
dataBuf.len = size.ULONG
var bytesReceived: Dword
var flagsio = flags.toOSFlags().Dword
var bytesReceived: DWORD
var flagsio = flags.toOSFlags().DWORD
var ol = PCustomOverlapped()
GC_ref(ol)
ol.data = CompletionData(fd: socket, cb:
proc (fd: AsyncFD, bytesCount: Dword, errcode: OSErrorCode) =
proc (fd: AsyncFD, bytesCount: DWORD, errcode: OSErrorCode) =
if not retFuture.finished:
if errcode == OSErrorCode(-1):
retFuture.complete(bytesCount)
@ -556,11 +556,11 @@ when defined(windows) or defined(nimdoc):
dataBuf.buf = cast[cstring](buf)
dataBuf.len = size.ULONG
var bytesReceived, lowFlags: Dword
var bytesReceived, lowFlags: DWORD
var ol = PCustomOverlapped()
GC_ref(ol)
ol.data = CompletionData(fd: socket, cb:
proc (fd: AsyncFD, bytesCount: Dword, errcode: OSErrorCode) =
proc (fd: AsyncFD, bytesCount: DWORD, errcode: OSErrorCode) =
if not retFuture.finished:
if errcode == OSErrorCode(-1):
retFuture.complete()
@ -589,7 +589,7 @@ when defined(windows) or defined(nimdoc):
return retFuture
proc sendTo*(socket: AsyncFD, data: pointer, size: int, saddr: ptr SockAddr,
saddrLen: Socklen,
saddrLen: SockLen,
flags = {SocketFlag.SafeDisconn}): owned(Future[void]) =
## Sends ``data`` to specified destination ``saddr``, using
## socket ``socket``. The returned future will complete once all data
@ -599,8 +599,8 @@ when defined(windows) or defined(nimdoc):
var dataBuf: TWSABuf
dataBuf.buf = cast[cstring](data)
dataBuf.len = size.ULONG
var bytesSent = 0.Dword
var lowFlags = 0.Dword
var bytesSent = 0.DWORD
var lowFlags = 0.DWORD
# we will preserve address in our stack
var staddr: array[128, char] # SOCKADDR_STORAGE size is 128 bytes
@ -611,7 +611,7 @@ when defined(windows) or defined(nimdoc):
var ol = PCustomOverlapped()
GC_ref(ol)
ol.data = CompletionData(fd: socket, cb:
proc (fd: AsyncFD, bytesCount: Dword, errcode: OSErrorCode) =
proc (fd: AsyncFD, bytesCount: DWORD, errcode: OSErrorCode) =
if not retFuture.finished:
if errcode == OSErrorCode(-1):
retFuture.complete()
@ -647,13 +647,13 @@ when defined(windows) or defined(nimdoc):
var dataBuf = TWSABuf(buf: cast[cstring](data), len: size.ULONG)
var bytesReceived = 0.Dword
var lowFlags = 0.Dword
var bytesReceived = 0.DWORD
var lowFlags = 0.DWORD
var ol = PCustomOverlapped()
GC_ref(ol)
ol.data = CompletionData(fd: socket, cb:
proc (fd: AsyncFD, bytesCount: Dword, errcode: OSErrorCode) =
proc (fd: AsyncFD, bytesCount: DWORD, errcode: OSErrorCode) =
if not retFuture.finished:
if errcode == OSErrorCode(-1):
assert bytesCount <= size
@ -704,10 +704,10 @@ when defined(windows) or defined(nimdoc):
const lpOutputLen = 1024
var lpOutputBuf = newString(lpOutputLen)
var dwBytesReceived: Dword
let dwReceiveDataLength = 0.Dword # We don't want any data to be read.
let dwLocalAddressLength = Dword(sizeof(Sockaddr_in6) + 16)
let dwRemoteAddressLength = Dword(sizeof(Sockaddr_in6) + 16)
var dwBytesReceived: DWORD
let dwReceiveDataLength = 0.DWORD # We don't want any data to be read.
let dwLocalAddressLength = DWORD(sizeof(Sockaddr_in6) + 16)
let dwRemoteAddressLength = DWORD(sizeof(Sockaddr_in6) + 16)
template failAccept(errcode) =
if flags.isDisconnectionError(errcode):
@ -728,17 +728,17 @@ when defined(windows) or defined(nimdoc):
sizeof(listenSock).SockLen)
if setoptRet != 0:
let errcode = osLastError()
discard clientSock.closeSocket()
discard clientSock.closesocket()
failAccept(errcode)
else:
var localSockaddr, remoteSockaddr: ptr SockAddr
var localLen, remoteLen: int32
getAcceptExSockaddrs(addr lpOutputBuf[0], dwReceiveDataLength,
getAcceptExSockAddrs(addr lpOutputBuf[0], dwReceiveDataLength,
dwLocalAddressLength, dwRemoteAddressLength,
addr localSockaddr, addr localLen,
addr remoteSockaddr, addr remoteLen)
try:
let address = getAddrString(remoteSockAddr)
let address = getAddrString(remoteSockaddr)
register(clientSock.AsyncFD)
retFuture.complete((address: address, client: clientSock.AsyncFD))
except:
@ -749,7 +749,7 @@ when defined(windows) or defined(nimdoc):
var ol = PCustomOverlapped()
GC_ref(ol)
ol.data = CompletionData(fd: socket, cb:
proc (fd: AsyncFD, bytesCount: Dword, errcode: OSErrorCode) =
proc (fd: AsyncFD, bytesCount: DWORD, errcode: OSErrorCode) =
if not retFuture.finished:
if errcode == OSErrorCode(-1):
completeAccept()
@ -793,14 +793,14 @@ when defined(windows) or defined(nimdoc):
proc waitableCallback(param: pointer,
timerOrWaitFired: WINBOOL): void {.stdcall.} =
var p = cast[PostCallbackDataPtr](param)
discard postQueuedCompletionStatus(p.ioPort, timerOrWaitFired.Dword,
discard postQueuedCompletionStatus(p.ioPort, timerOrWaitFired.DWORD,
ULONG_PTR(p.handleFd),
cast[pointer](p.ovl))
{.pop.}
proc registerWaitableEvent(fd: AsyncFD, cb: Callback; mask: Dword) =
proc registerWaitableEvent(fd: AsyncFD, cb: Callback; mask: DWORD) =
let p = getGlobalDispatcher()
var flags = (WT_EXECUTEINWAITTHREAD or WT_EXECUTEONLYONCE).Dword
var flags = (WT_EXECUTEINWAITTHREAD or WT_EXECUTEONLYONCE).DWORD
var hEvent = wsaCreateEvent()
if hEvent == 0:
raiseOSError(osLastError())
@ -811,7 +811,7 @@ when defined(windows) or defined(nimdoc):
GC_ref(ol)
ol.data = CompletionData(fd: fd, cb:
proc(fd: AsyncFD, bytesCount: Dword, errcode: OSErrorCode) {.gcsafe.} =
proc(fd: AsyncFD, bytesCount: DWORD, errcode: OSErrorCode) {.gcsafe.} =
# we excluding our `fd` because cb(fd) can register own handler
# for this `fd`
p.handles.excl(fd)
@ -934,7 +934,7 @@ when defined(windows) or defined(nimdoc):
pcd.ovl = ol
if not registerWaitForSingleObject(addr(pcd.waitFd), hEvent,
cast[WAITORTIMERCALLBACK](waitableCallback),
cast[pointer](pcd), timeout.Dword, flags):
cast[pointer](pcd), timeout.DWORD, flags):
let err = osLastError()
GC_unref(ol)
deallocShared(cast[pointer](pcd))
@ -972,10 +972,10 @@ when defined(windows) or defined(nimdoc):
raiseOSError(osLastError())
var pcd = cast[PostCallbackDataPtr](allocShared0(sizeof(PostCallbackData)))
var flags = WT_EXECUTEINWAITTHREAD.Dword
var flags = WT_EXECUTEINWAITTHREAD.DWORD
if oneshot: flags = flags or WT_EXECUTEONLYONCE
proc timercb(fd: AsyncFD, bytesCount: Dword, errcode: OSErrorCode) =
proc timercb(fd: AsyncFD, bytesCount: DWORD, errcode: OSErrorCode) =
let res = cb(fd)
if res or oneshot:
closeWaitable(hEvent)
@ -993,14 +993,14 @@ when defined(windows) or defined(nimdoc):
## ``pid`` exited.
let p = getGlobalDispatcher()
let procFlags = SYNCHRONIZE
var hProcess = openProcess(procFlags, 0, pid.Dword)
var hProcess = openProcess(procFlags, 0, pid.DWORD)
if hProcess == INVALID_HANDLE_VALUE:
raiseOSError(osLastError())
var pcd = cast[PostCallbackDataPtr](allocShared0(sizeof(PostCallbackData)))
var flags = WT_EXECUTEINWAITTHREAD.Dword
var flags = WT_EXECUTEINWAITTHREAD.DWORD
proc proccb(fd: AsyncFD, bytesCount: Dword, errcode: OSErrorCode) =
proc proccb(fd: AsyncFD, bytesCount: DWORD, errcode: OSErrorCode) =
closeWaitable(hProcess)
discard cb(fd)
@ -1052,9 +1052,9 @@ when defined(windows) or defined(nimdoc):
let hEvent = ev.hEvent
var pcd = cast[PostCallbackDataPtr](allocShared0(sizeof(PostCallbackData)))
var flags = WT_EXECUTEINWAITTHREAD.Dword
var flags = WT_EXECUTEINWAITTHREAD.DWORD
proc eventcb(fd: AsyncFD, bytesCount: Dword, errcode: OSErrorCode) =
proc eventcb(fd: AsyncFD, bytesCount: DWORD, errcode: OSErrorCode) =
if ev.hWaiter != 0:
if cb(fd):
# we need this check to avoid exception, if `unregister(event)` was
@ -1615,7 +1615,7 @@ when defined(windows) or defined(nimdoc):
var ol = PCustomOverlapped()
GC_ref(ol)
ol.data = CompletionData(fd: socket, cb:
proc (fd: AsyncFD, bytesCount: Dword, errcode: OSErrorCode) =
proc (fd: AsyncFD, bytesCount: DWORD, errcode: OSErrorCode) =
if not retFuture.finished:
if errcode == OSErrorCode(-1):
retFuture.complete()
@ -1708,7 +1708,7 @@ template asyncAddrInfoLoop(addrInfo: ptr AddrInfo, fd: untyped,
curAddrInfo = curAddrInfo.ai_next
if curAddrInfo == nil:
freeAddrInfo(addrInfo)
freeaddrinfo(addrInfo)
when shouldCreateFd:
closeUnusedFds()
if lastException != nil:
@ -1724,7 +1724,7 @@ template asyncAddrInfoLoop(addrInfo: ptr AddrInfo, fd: untyped,
try:
curFd = createAsyncNativeSocket(domain, sockType, protocol)
except:
freeAddrInfo(addrInfo)
freeaddrinfo(addrInfo)
closeUnusedFds()
raise getCurrentException()
when defined(windows):
@ -1734,7 +1734,7 @@ template asyncAddrInfoLoop(addrInfo: ptr AddrInfo, fd: untyped,
doConnect(curFd, curAddrInfo).callback = tryNextAddrInfo
curAddrInfo = curAddrInfo.ai_next
else:
freeAddrInfo(addrInfo)
freeaddrinfo(addrInfo)
when shouldCreateFd:
closeUnusedFds(ord(domain))
retFuture.complete(curFd)

View file

@ -303,7 +303,7 @@ proc `$`*(entries: seq[StackTraceEntry]): string =
# Find longest filename & line number combo for alignment purposes.
var longestLeft = 0
for entry in entries:
if entry.procName.isNil: continue
if entry.procname.isNil: continue
let left = $entry.filename & $entry.line
if left.len > longestLeft:
@ -312,7 +312,7 @@ proc `$`*(entries: seq[StackTraceEntry]): string =
var indent = 2
# Format the entries.
for entry in entries:
if entry.procName.isNil:
if entry.procname.isNil:
if entry.line == -10:
result.add(spaces(indent) & "#[\n")
indent.inc(2)
@ -325,7 +325,7 @@ proc `$`*(entries: seq[StackTraceEntry]): string =
result.add((spaces(indent) & "$#$# $#\n") % [
left,
spaces(longestLeft - left.len + 2),
$entry.procName
$entry.procname
])
let hint = getHint(entry)
if hint.len > 0:

View file

@ -121,7 +121,7 @@ when defined(nimHasalignOf):
# #### Pure Nim version ####
proc firstSetBit_nim(x: uint32): int {.inline, nosideeffect.} =
proc firstSetBitNim(x: uint32): int {.inline, noSideEffect.} =
## Returns the 1-based index of the least significant set bit of x, or if x is zero, returns zero.
# https://graphics.stanford.edu/%7Eseander/bithacks.html#ZerosOnRightMultLookup
const lookup: array[32, uint8] = [0'u8, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15,
@ -130,7 +130,7 @@ proc firstSetBit_nim(x: uint32): int {.inline, nosideeffect.} =
var k = not v + 1 # get two's complement # cast[uint32](-cast[int32](v))
result = 1 + lookup[uint32((v and k) * 0x077CB531'u32) shr 27].int
proc firstSetBit_nim(x: uint64): int {.inline, nosideeffect.} =
proc firstSetBitNim(x: uint64): int {.inline, noSideEffect.} =
## Returns the 1-based index of the least significant set bit of x, or if x is zero, returns zero.
# https://graphics.stanford.edu/%7Eseander/bithacks.html#ZerosOnRightMultLookup
var v = uint64(x)
@ -138,9 +138,9 @@ proc firstSetBit_nim(x: uint64): int {.inline, nosideeffect.} =
if k == 0:
k = uint32(v shr 32'u32) and 0xFFFFFFFF'u32
result = 32
result += firstSetBit_nim(k)
result += firstSetBitNim(k)
proc fastlog2_nim(x: uint32): int {.inline, nosideeffect.} =
proc fastlog2Nim(x: uint32): int {.inline, noSideEffect.} =
## Quickly find the log base 2 of a 32-bit or less integer.
# https://graphics.stanford.edu/%7Eseander/bithacks.html#IntegerLogDeBruijn
# https://stackoverflow.com/questions/11376288/fast-computing-of-log2-for-64-bit-integers
@ -154,7 +154,7 @@ proc fastlog2_nim(x: uint32): int {.inline, nosideeffect.} =
v = v or v shr 16
result = lookup[uint32(v * 0x07C4ACDD'u32) shr 27].int
proc fastlog2_nim(x: uint64): int {.inline, nosideeffect.} =
proc fastlog2Nim(x: uint64): int {.inline, noSideEffect.} =
## Quickly find the log base 2 of a 64-bit integer.
# https://graphics.stanford.edu/%7Eseander/bithacks.html#IntegerLogDeBruijn
# https://stackoverflow.com/questions/11376288/fast-computing-of-log2-for-64-bit-integers
@ -176,10 +176,10 @@ proc fastlog2_nim(x: uint64): int {.inline, nosideeffect.} =
# countBits32 and countBits64.
include system/sets
template countSetBits_nim(n: uint32): int = countBits32(n)
template countSetBits_nim(n: uint64): int = countBits64(n)
template countSetBitsNim(n: uint32): int = countBits32(n)
template countSetBitsNim(n: uint64): int = countBits64(n)
template parity_impl[T](value: T): int =
template parityImpl[T](value: T): int =
# formula id from: https://graphics.stanford.edu/%7Eseander/bithacks.html#ParityParallel
var v = value
when sizeof(T) == 8:
@ -216,17 +216,17 @@ when useGCC_builtins:
elif useVCC_builtins:
# Counts the number of one bits (population count) in a 16-, 32-, or 64-byte unsigned integer.
proc builtin_popcnt16(a2: uint16): uint16 {.importc: "__popcnt16" header: "<intrin.h>", nosideeffect.}
proc builtin_popcnt32(a2: uint32): uint32 {.importc: "__popcnt" header: "<intrin.h>", nosideeffect.}
proc builtin_popcnt64(a2: uint64): uint64 {.importc: "__popcnt64" header: "<intrin.h>", nosideeffect.}
proc builtin_popcnt16(a2: uint16): uint16 {.importc: "__popcnt16" header: "<intrin.h>", noSideEffect.}
proc builtin_popcnt32(a2: uint32): uint32 {.importc: "__popcnt" header: "<intrin.h>", noSideEffect.}
proc builtin_popcnt64(a2: uint64): uint64 {.importc: "__popcnt64" header: "<intrin.h>", noSideEffect.}
# Search the mask data from most significant bit (MSB) to least significant bit (LSB) for a set bit (1).
proc bitScanReverse(index: ptr culong, mask: culong): cuchar {.importc: "_BitScanReverse", header: "<intrin.h>", nosideeffect.}
proc bitScanReverse64(index: ptr culong, mask: uint64): cuchar {.importc: "_BitScanReverse64", header: "<intrin.h>", nosideeffect.}
proc bitScanReverse(index: ptr culong, mask: culong): cuchar {.importc: "_BitScanReverse", header: "<intrin.h>", noSideEffect.}
proc bitScanReverse64(index: ptr culong, mask: uint64): cuchar {.importc: "_BitScanReverse64", header: "<intrin.h>", noSideEffect.}
# Search the mask data from least significant bit (LSB) to the most significant bit (MSB) for a set bit (1).
proc bitScanForward(index: ptr culong, mask: culong): cuchar {.importc: "_BitScanForward", header: "<intrin.h>", nosideeffect.}
proc bitScanForward64(index: ptr culong, mask: uint64): cuchar {.importc: "_BitScanForward64", header: "<intrin.h>", nosideeffect.}
proc bitScanForward(index: ptr culong, mask: culong): cuchar {.importc: "_BitScanForward", header: "<intrin.h>", noSideEffect.}
proc bitScanForward64(index: ptr culong, mask: uint64): cuchar {.importc: "_BitScanForward64", header: "<intrin.h>", noSideEffect.}
template vcc_scan_impl(fnc: untyped; v: untyped): int =
var index: culong
@ -238,16 +238,16 @@ elif useICC_builtins:
# Intel compiler intrinsics: http://fulla.fnal.gov/intel/compiler_c/main_cls/intref_cls/common/intref_allia_misc.htm
# see also: https://software.intel.com/en-us/node/523362
# Count the number of bits set to 1 in an integer a, and return that count in dst.
proc builtin_popcnt32(a: cint): cint {.importc: "_popcnt" header: "<immintrin.h>", nosideeffect.}
proc builtin_popcnt64(a: uint64): cint {.importc: "_popcnt64" header: "<immintrin.h>", nosideeffect.}
proc builtin_popcnt32(a: cint): cint {.importc: "_popcnt" header: "<immintrin.h>", noSideEffect.}
proc builtin_popcnt64(a: uint64): cint {.importc: "_popcnt64" header: "<immintrin.h>", noSideEffect.}
# Returns the number of trailing 0-bits in x, starting at the least significant bit position. If x is 0, the result is undefined.
proc bitScanForward(p: ptr uint32, b: uint32): cuchar {.importc: "_BitScanForward", header: "<immintrin.h>", nosideeffect.}
proc bitScanForward64(p: ptr uint32, b: uint64): cuchar {.importc: "_BitScanForward64", header: "<immintrin.h>", nosideeffect.}
proc bitScanForward(p: ptr uint32, b: uint32): cuchar {.importc: "_BitScanForward", header: "<immintrin.h>", noSideEffect.}
proc bitScanForward64(p: ptr uint32, b: uint64): cuchar {.importc: "_BitScanForward64", header: "<immintrin.h>", noSideEffect.}
# Returns the number of leading 0-bits in x, starting at the most significant bit position. If x is 0, the result is undefined.
proc bitScanReverse(p: ptr uint32, b: uint32): cuchar {.importc: "_BitScanReverse", header: "<immintrin.h>", nosideeffect.}
proc bitScanReverse64(p: ptr uint32, b: uint64): cuchar {.importc: "_BitScanReverse64", header: "<immintrin.h>", nosideeffect.}
proc bitScanReverse(p: ptr uint32, b: uint32): cuchar {.importc: "_BitScanReverse", header: "<immintrin.h>", noSideEffect.}
proc bitScanReverse64(p: ptr uint32, b: uint64): cuchar {.importc: "_BitScanReverse64", header: "<immintrin.h>", noSideEffect.}
template icc_scan_impl(fnc: untyped; v: untyped): int =
var index: uint32
@ -255,14 +255,14 @@ elif useICC_builtins:
index.int
proc countSetBits*(x: SomeInteger): int {.inline, nosideeffect.} =
proc countSetBits*(x: SomeInteger): int {.inline, noSideEffect.} =
## Counts the set bits in integer. (also called `Hamming weight`:idx:.)
# TODO: figure out if ICC support _popcnt32/_popcnt64 on platform without POPCNT.
# like GCC and MSVC
when x is SomeSignedInt:
let x = x.toUnsigned
when nimvm:
result = forwardImpl(countSetBits_nim, x)
result = forwardImpl(countSetBitsNim, x)
else:
when useGCC_builtins:
when sizeof(x) <= 4: result = builtin_popcount(x.cuint).int
@ -279,14 +279,14 @@ proc countSetBits*(x: SomeInteger): int {.inline, nosideeffect.} =
else: result = builtin_popcnt32((x.uint64 and 0xFFFFFFFF'u64).cint ).int +
builtin_popcnt32((x.uint64 shr 32'u64).cint ).int
else:
when sizeof(x) <= 4: result = countSetBits_nim(x.uint32)
else: result = countSetBits_nim(x.uint64)
when sizeof(x) <= 4: result = countSetBitsNim(x.uint32)
else: result = countSetBitsNim(x.uint64)
proc popcount*(x: SomeInteger): int {.inline, nosideeffect.} =
proc popcount*(x: SomeInteger): int {.inline, noSideEffect.} =
## Alias for for countSetBits (Hamming weight.)
result = countSetBits(x)
proc parityBits*(x: SomeInteger): int {.inline, nosideeffect.} =
proc parityBits*(x: SomeInteger): int {.inline, noSideEffect.} =
## Calculate the bit parity in integer. If number of 1-bit
## is odd parity is 1, otherwise 0.
# Can be used a base if creating ASM version.
@ -294,16 +294,16 @@ proc parityBits*(x: SomeInteger): int {.inline, nosideeffect.} =
when x is SomeSignedInt:
let x = x.toUnsigned
when nimvm:
result = forwardImpl(parity_impl, x)
result = forwardImpl(parityImpl, x)
else:
when useGCC_builtins:
when sizeof(x) <= 4: result = builtin_parity(x.uint32).int
else: result = builtin_parityll(x.uint64).int
else:
when sizeof(x) <= 4: result = parity_impl(x.uint32)
else: result = parity_impl(x.uint64)
when sizeof(x) <= 4: result = parityImpl(x.uint32)
else: result = parityImpl(x.uint64)
proc firstSetBit*(x: SomeInteger): int {.inline, nosideeffect.} =
proc firstSetBit*(x: SomeInteger): int {.inline, noSideEffect.} =
## Returns the 1-based index of the least significant set bit of x.
## If `x` is zero, when ``noUndefinedBitOpts`` is set, result is 0,
## otherwise result is undefined.
@ -314,7 +314,7 @@ proc firstSetBit*(x: SomeInteger): int {.inline, nosideeffect.} =
when noUndefined:
if x == 0:
return 0
result = forwardImpl(firstSetBit_nim, x)
result = forwardImpl(firstSetBitNim, x)
else:
when noUndefined and not useGCC_builtins:
if x == 0:
@ -328,19 +328,19 @@ proc firstSetBit*(x: SomeInteger): int {.inline, nosideeffect.} =
elif arch64:
result = 1 + vcc_scan_impl(bitScanForward64, x.uint64)
else:
result = firstSetBit_nim(x.uint64)
result = firstSetBitNim(x.uint64)
elif useICC_builtins:
when sizeof(x) <= 4:
result = 1 + icc_scan_impl(bitScanForward, x.uint32)
elif arch64:
result = 1 + icc_scan_impl(bitScanForward64, x.uint64)
else:
result = firstSetBit_nim(x.uint64)
result = firstSetBitNim(x.uint64)
else:
when sizeof(x) <= 4: result = firstSetBit_nim(x.uint32)
else: result = firstSetBit_nim(x.uint64)
when sizeof(x) <= 4: result = firstSetBitNim(x.uint32)
else: result = firstSetBitNim(x.uint64)
proc fastLog2*(x: SomeInteger): int {.inline, nosideeffect.} =
proc fastLog2*(x: SomeInteger): int {.inline, noSideEffect.} =
## Quickly find the log base 2 of an integer.
## If `x` is zero, when ``noUndefinedBitOpts`` is set, result is -1,
## otherwise result is undefined.
@ -350,7 +350,7 @@ proc fastLog2*(x: SomeInteger): int {.inline, nosideeffect.} =
if x == 0:
return -1
when nimvm:
result = forwardImpl(fastlog2_nim, x)
result = forwardImpl(fastlog2Nim, x)
else:
when useGCC_builtins:
when sizeof(x) <= 4: result = 31 - builtin_clz(x.uint32).int
@ -361,19 +361,19 @@ proc fastLog2*(x: SomeInteger): int {.inline, nosideeffect.} =
elif arch64:
result = vcc_scan_impl(bitScanReverse64, x.uint64)
else:
result = fastlog2_nim(x.uint64)
result = fastlog2Nim(x.uint64)
elif useICC_builtins:
when sizeof(x) <= 4:
result = icc_scan_impl(bitScanReverse, x.uint32)
elif arch64:
result = icc_scan_impl(bitScanReverse64, x.uint64)
else:
result = fastlog2_nim(x.uint64)
result = fastlog2Nim(x.uint64)
else:
when sizeof(x) <= 4: result = fastlog2_nim(x.uint32)
else: result = fastlog2_nim(x.uint64)
when sizeof(x) <= 4: result = fastlog2Nim(x.uint32)
else: result = fastlog2Nim(x.uint64)
proc countLeadingZeroBits*(x: SomeInteger): int {.inline, nosideeffect.} =
proc countLeadingZeroBits*(x: SomeInteger): int {.inline, noSideEffect.} =
## Returns the number of leading zero bits in integer.
## If `x` is zero, when ``noUndefinedBitOpts`` is set, result is 0,
## otherwise result is undefined.
@ -383,16 +383,16 @@ proc countLeadingZeroBits*(x: SomeInteger): int {.inline, nosideeffect.} =
if x == 0:
return 0
when nimvm:
result = sizeof(x)*8 - 1 - forwardImpl(fastlog2_nim, x)
result = sizeof(x)*8 - 1 - forwardImpl(fastlog2Nim, x)
else:
when useGCC_builtins:
when sizeof(x) <= 4: result = builtin_clz(x.uint32).int - (32 - sizeof(x)*8)
else: result = builtin_clzll(x.uint64).int
else:
when sizeof(x) <= 4: result = sizeof(x)*8 - 1 - fastlog2_nim(x.uint32)
else: result = sizeof(x)*8 - 1 - fastlog2_nim(x.uint64)
when sizeof(x) <= 4: result = sizeof(x)*8 - 1 - fastlog2Nim(x.uint32)
else: result = sizeof(x)*8 - 1 - fastlog2Nim(x.uint64)
proc countTrailingZeroBits*(x: SomeInteger): int {.inline, nosideeffect.} =
proc countTrailingZeroBits*(x: SomeInteger): int {.inline, noSideEffect.} =
## Returns the number of trailing zeros in integer.
## If `x` is zero, when ``noUndefinedBitOpts`` is set, result is 0,
## otherwise result is undefined.
@ -471,7 +471,7 @@ proc repeatBits[T: SomeUnsignedInt](x: SomeUnsignedInt; retType: type[T]): T {.
while i != (sizeof(T) div sizeof(x)):
result = (result shl (sizeof(x)*8*i)) or result
i *= 2
proc reverseBits*[T: SomeUnsignedInt](x: T): T {.noSideEffect.} =
## Return the bit reversal of x.
runnableExamples:

View file

@ -286,7 +286,7 @@ proc enlarge[A, B](t: var Table[A, B]) =
# ------------------------------ Table ------------------------------
# -------------------------------------------------------------------
proc initTable*[A, B](initialsize = defaultInitialSize): Table[A, B] =
proc initTable*[A, B](initialSize = defaultInitialSize): Table[A, B] =
## Creates a new hash table that is empty.
##
## ``initialSize`` must be a power of two (default: 64).
@ -1263,7 +1263,7 @@ template forAllOrderedPairs(yieldStmt: untyped) {.dirty.} =
# ----------------------------------------------------------------------
proc initOrderedTable*[A, B](initialsize = defaultInitialSize): OrderedTable[A, B] =
proc initOrderedTable*[A, B](initialSize = defaultInitialSize): OrderedTable[A, B] =
## Creates a new ordered hash table that is empty.
##
## ``initialSize`` must be a power of two (default: 64).
@ -2185,7 +2185,7 @@ proc inc*[A](t: var CountTable[A], key: A, val = 1)
# ----------------------------------------------------------------------
proc initCountTable*[A](initialsize = defaultInitialSize): CountTable[A] =
proc initCountTable*[A](initialSize = defaultInitialSize): CountTable[A] =
## Creates a new count table that is empty.
##
## ``initialSize`` must be a power of two (default: 64).

View file

@ -59,7 +59,7 @@ import strutils
type
LibHandle* = pointer ## a handle to a dynamically loaded library
proc loadLib*(path: string, global_symbols=false): LibHandle {.gcsafe.}
proc loadLib*(path: string, globalSymbols=false): LibHandle {.gcsafe.}
## loads a library from `path`. Returns nil if the library could not
## be loaded.
@ -96,14 +96,14 @@ proc libCandidates*(s: string, dest: var seq[string]) =
else:
add(dest, s)
proc loadLibPattern*(pattern: string, global_symbols=false): LibHandle =
proc loadLibPattern*(pattern: string, globalSymbols=false): LibHandle =
## loads a library with name matching `pattern`, similar to what `dlimport`
## pragma does. Returns nil if the library could not be loaded.
## Warning: this proc uses the GC and so cannot be used to load the GC.
var candidates = newSeq[string]()
libCandidates(pattern, candidates)
for c in candidates:
result = loadLib(c, global_symbols)
result = loadLib(c, globalSymbols)
if not result.isNil: break
when defined(posix) and not defined(nintendoswitch):
@ -117,9 +117,9 @@ when defined(posix) and not defined(nintendoswitch):
#
import posix
proc loadLib(path: string, global_symbols=false): LibHandle =
proc loadLib(path: string, globalSymbols=false): LibHandle =
let flags =
if global_symbols: RTLD_NOW or RTLD_GLOBAL
if globalSymbols: RTLD_NOW or RTLD_GLOBAL
else: RTLD_NOW
dlopen(path, flags)
@ -170,7 +170,7 @@ elif defined(windows) or defined(dos):
proc getProcAddress(lib: THINSTANCE, name: cstring): pointer {.
importc: "GetProcAddress", header: "<windows.h>", stdcall.}
proc loadLib(path: string, global_symbols=false): LibHandle =
proc loadLib(path: string, globalSymbols=false): LibHandle =
result = cast[LibHandle](winLoadLibrary(path))
proc loadLib(): LibHandle =
result = cast[LibHandle](winLoadLibrary(nil))

View file

@ -13,33 +13,33 @@
when defined(gcc) or defined(llvm_gcc) or defined(clang):
const useBuiltinSwap = true
proc builtin_bswap16(a: uint16): uint16 {.
importc: "__builtin_bswap16", nodecl, nosideeffect.}
importc: "__builtin_bswap16", nodecl, noSideEffect.}
proc builtin_bswap32(a: uint32): uint32 {.
importc: "__builtin_bswap32", nodecl, nosideeffect.}
importc: "__builtin_bswap32", nodecl, noSideEffect.}
proc builtin_bswap64(a: uint64): uint64 {.
importc: "__builtin_bswap64", nodecl, nosideeffect.}
importc: "__builtin_bswap64", nodecl, noSideEffect.}
elif defined(icc):
const useBuiltinSwap = true
proc builtin_bswap16(a: uint16): uint16 {.
importc: "_bswap16", nodecl, nosideeffect.}
importc: "_bswap16", nodecl, noSideEffect.}
proc builtin_bswap32(a: uint32): uint32 {.
importc: "_bswap", nodecl, nosideeffect.}
importc: "_bswap", nodecl, noSideEffect.}
proc builtin_bswap64(a: uint64): uint64 {.
importc: "_bswap64", nodecl, nosideeffect.}
importc: "_bswap64", nodecl, noSideEffect.}
elif defined(vcc):
const useBuiltinSwap = true
proc builtin_bswap16(a: uint16): uint16 {.
importc: "_byteswap_ushort", nodecl, header: "<intrin.h>", nosideeffect.}
importc: "_byteswap_ushort", nodecl, header: "<intrin.h>", noSideEffect.}
proc builtin_bswap32(a: uint32): uint32 {.
importc: "_byteswap_ulong", nodecl, header: "<intrin.h>", nosideeffect.}
importc: "_byteswap_ulong", nodecl, header: "<intrin.h>", noSideEffect.}
proc builtin_bswap64(a: uint64): uint64 {.
importc: "_byteswap_uint64", nodecl, header: "<intrin.h>", nosideeffect.}
importc: "_byteswap_uint64", nodecl, header: "<intrin.h>", noSideEffect.}
else:
const useBuiltinSwap = false
@ -49,17 +49,17 @@ when useBuiltinSwap:
## may point to a unaligned address. A sufficiently smart compiler _should_
## be able to elide them when they're not necessary.
var tmp: T
copyMem(addr tmp, inp, sizeOf(T))
copyMem(addr tmp, inp, sizeof(T))
tmp = op(tmp)
copyMem(outp, addr tmp, sizeOf(T))
copyMem(outp, addr tmp, sizeof(T))
proc swapEndian64*(outp, inp: pointer) {.inline, nosideeffect.}=
proc swapEndian64*(outp, inp: pointer) {.inline, noSideEffect.}=
swapOpImpl(uint64, builtin_bswap64)
proc swapEndian32*(outp, inp: pointer) {.inline, nosideeffect.}=
proc swapEndian32*(outp, inp: pointer) {.inline, noSideEffect.}=
swapOpImpl(uint32, builtin_bswap32)
proc swapEndian16*(outp, inp: pointer) {.inline, nosideeffect.}=
proc swapEndian16*(outp, inp: pointer) {.inline, noSideEffect.}=
swapOpImpl(uint16, builtin_bswap16)
else:

View file

@ -169,7 +169,7 @@ template hashImpl(result: Hash, x: typed, start, stop: int) =
var n = 0
when nimvm:
# we cannot cast in VM, so we do it manually
for j in countdown(stepsize-1, 0):
for j in countdown(stepSize-1, 0):
n = (n shl (8*elementSize)) or ord(x[i+j])
else:
n = cast[ptr Hash](unsafeAddr x[i])[]

View file

@ -324,7 +324,7 @@ proc `%`*(b: bool): JsonNode =
proc `%`*(keyVals: openArray[tuple[key: string, val: JsonNode]]): JsonNode =
## Generic constructor for JSON data. Creates a new `JObject JsonNode`
if keyvals.len == 0: return newJArray()
if keyVals.len == 0: return newJArray()
result = newJObject()
for key, val in items(keyVals): result.fields[key] = val
@ -380,7 +380,7 @@ proc `%`*(o: enum): JsonNode =
## string. Creates a new ``JString JsonNode``.
result = %($o)
proc toJson(x: NimNode): NimNode {.compiletime.} =
proc toJson(x: NimNode): NimNode {.compileTime.} =
case x.kind
of nnkBracket: # array
if x.len == 0: return newCall(bindSym"newJArray")

View file

@ -15,6 +15,9 @@
## * `hashes module<hashes.html>`_ for efficient computations of hash values
## for diverse Nim types
when defined(nimHasStyleChecks):
{.push styleChecks: off.}
type
MD5State = array[0..3, uint32]
MD5Block = array[0..15, uint32]
@ -197,7 +200,7 @@ proc `$`*(d: MD5Digest): string =
add(result, digits[d[i].int and 0xF])
proc getMD5*(s: string): string =
## Computes an MD5 value of `s` and returns its string representation.
## Computes an MD5 value of `s` and returns its string representation.
## .. note::
## available at compile time
##
@ -232,7 +235,7 @@ proc md5Init*(c: var MD5Context) =
c.state[3] = 0x10325476'u32
c.count[0] = 0'u32
c.count[1] = 0'u32
zeroMem(addr(c.buffer), sizeof(MD5buffer))
zeroMem(addr(c.buffer), sizeof(MD5Buffer))
proc md5Update*(c: var MD5Context, input: cstring, len: int) =
## Updates the `MD5Context` with the `input` data of length `len`.
@ -280,3 +283,6 @@ when isMainModule:
assert(getMD5("Frank jagt im komplett verwahrlosten Taxi quer durch Bayern") ==
"7e716d0e702df0505fc72e2b89467910")
assert($toMD5("") == "d41d8cd98f00b204e9800998ecf8427e")
when defined(nimHasStyleChecks):
{.pop.} #{.push styleChecks: off.}

View file

@ -354,11 +354,11 @@ proc getHostByAddr*(ip: string): Hostent {.tags: [ReadIOEffect].} =
else:
raiseOSError(osLastError(), "unknown h_addrtype")
if result.addrtype == AF_INET:
result.addrlist = @[]
result.addrList = @[]
var i = 0
while not isNil(s.h_addrlist[i]):
while not isNil(s.h_addr_list[i]):
var inaddr_ptr = cast[ptr InAddr](s.h_addr_list[i])
result.addrlist.add($inet_ntoa(inaddr_ptr[]))
result.addrList.add($inet_ntoa(inaddr_ptr[]))
inc(i)
else:
result.addrList = cstringArrayToSeq(s.h_addr_list)
@ -383,11 +383,11 @@ proc getHostByName*(name: string): Hostent {.tags: [ReadIOEffect].} =
else:
raiseOSError(osLastError(), "unknown h_addrtype")
if result.addrtype == AF_INET:
result.addrlist = @[]
result.addrList = @[]
var i = 0
while not isNil(s.h_addrlist[i]):
while not isNil(s.h_addr_list[i]):
var inaddr_ptr = cast[ptr InAddr](s.h_addr_list[i])
result.addrlist.add($inet_ntoa(inaddr_ptr[]))
result.addrList.add($inet_ntoa(inaddr_ptr[]))
inc(i)
else:
result.addrList = cstringArrayToSeq(s.h_addr_list)
@ -400,7 +400,7 @@ proc getHostname*(): string {.tags: [ReadIOEffect].} =
const size = 64
result = newString(size)
when useWinVersion:
let success = winlean.getHostname(result, size)
let success = winlean.gethostname(result, size)
else:
# Posix
let success = posix.getHostname(result, size)
@ -613,7 +613,7 @@ proc selectRead*(readfds: var seq[SocketHandle], timeout = 500): int =
##
## ``timeout`` is specified in milliseconds and ``-1`` can be specified for
## an unlimited time.
var tv {.noInit.}: Timeval = timeValFromMilliseconds(timeout)
var tv {.noinit.}: Timeval = timeValFromMilliseconds(timeout)
var rd: TFdSet
var m = 0
@ -635,7 +635,7 @@ proc selectWrite*(writefds: var seq[SocketHandle],
##
## ``timeout`` is specified in milliseconds and ``-1`` can be specified for
## an unlimited time.
var tv {.noInit.}: Timeval = timeValFromMilliseconds(timeout)
var tv {.noinit.}: Timeval = timeValFromMilliseconds(timeout)
var wr: TFdSet
var m = 0

View file

@ -398,35 +398,35 @@ proc isIpAddress*(addressStr: string): bool {.tags: [].} =
return true
proc toSockAddr*(address: IpAddress, port: Port, sa: var Sockaddr_storage,
sl: var Socklen) =
sl: var SockLen) =
## Converts `IpAddress` and `Port` to `SockAddr` and `Socklen`
let port = htons(uint16(port))
case address.family
of IpAddressFamily.IPv4:
sl = sizeof(Sockaddr_in).Socklen
sl = sizeof(Sockaddr_in).SockLen
let s = cast[ptr Sockaddr_in](addr sa)
s.sin_family = type(s.sin_family)(toInt(AF_INET))
s.sin_port = port
copyMem(addr s.sin_addr, unsafeAddr address.address_v4[0],
sizeof(s.sin_addr))
of IpAddressFamily.IPv6:
sl = sizeof(Sockaddr_in6).Socklen
sl = sizeof(Sockaddr_in6).SockLen
let s = cast[ptr Sockaddr_in6](addr sa)
s.sin6_family = type(s.sin6_family)(toInt(AF_INET6))
s.sin6_port = port
copyMem(addr s.sin6_addr, unsafeAddr address.address_v6[0],
sizeof(s.sin6_addr))
proc fromSockAddrAux(sa: ptr Sockaddr_storage, sl: Socklen,
proc fromSockAddrAux(sa: ptr Sockaddr_storage, sl: SockLen,
address: var IpAddress, port: var Port) =
if sa.ss_family.cint == toInt(AF_INET) and sl == sizeof(Sockaddr_in).Socklen:
if sa.ss_family.cint == toInt(AF_INET) and sl == sizeof(Sockaddr_in).SockLen:
address = IpAddress(family: IpAddressFamily.IPv4)
let s = cast[ptr Sockaddr_in](sa)
copyMem(addr address.address_v4[0], addr s.sin_addr,
sizeof(address.address_v4))
port = ntohs(s.sin_port).Port
elif sa.ss_family.cint == toInt(AF_INET6) and
sl == sizeof(Sockaddr_in6).Socklen:
sl == sizeof(Sockaddr_in6).SockLen:
address = IpAddress(family: IpAddressFamily.IPv6)
let s = cast[ptr Sockaddr_in6](sa)
copyMem(addr address.address_v6[0], addr s.sin6_addr,
@ -436,7 +436,7 @@ proc fromSockAddrAux(sa: ptr Sockaddr_storage, sl: Socklen,
raise newException(ValueError, "Neither IPv4 nor IPv6")
proc fromSockAddr*(sa: Sockaddr_storage | SockAddr | Sockaddr_in | Sockaddr_in6,
sl: Socklen, address: var IpAddress, port: var Port) {.inline.} =
sl: SockLen, address: var IpAddress, port: var Port) {.inline.} =
## Converts `SockAddr` and `Socklen` to `IpAddress` and `Port`. Raises
## `ObjectConversionError` in case of invalid `sa` and `sl` arguments.
fromSockAddrAux(cast[ptr Sockaddr_storage](unsafeAddr sa), sl, address, port)
@ -762,9 +762,9 @@ proc bindAddr*(socket: Socket, port = Port(0), address = "") {.
var aiList = getAddrInfo(realaddr, port, socket.domain)
if bindAddr(socket.fd, aiList.ai_addr, aiList.ai_addrlen.SockLen) < 0'i32:
freeAddrInfo(aiList)
freeaddrinfo(aiList)
raiseOSError(osLastError())
freeAddrInfo(aiList)
freeaddrinfo(aiList)
proc acceptAddr*(server: Socket, client: var owned(Socket), address: var string,
flags = {SocketFlag.SafeDisconn}) {.
@ -1378,7 +1378,7 @@ proc sendTo*(socket: Socket, address: string, port: Port, data: pointer,
it = it.ai_next
let osError = osLastError()
freeAddrInfo(aiList)
freeaddrinfo(aiList)
if not success:
raiseOSError(osError)
@ -1405,6 +1405,9 @@ proc isSsl*(socket: Socket): bool =
proc getFd*(socket: Socket): SocketHandle = return socket.fd
## Returns the socket's file descriptor
when defined(nimHasStyleChecks):
{.push styleChecks: off.}
proc IPv4_any*(): IpAddress =
## Returns the IPv4 any address, which can be used to listen on all available
## network adapters
@ -1437,6 +1440,9 @@ proc IPv6_loopback*(): IpAddress =
family: IpAddressFamily.IPv6,
address_v6: [0'u8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1])
when defined(nimHasStyleChecks):
{.pop.}
proc `==`*(lhs, rhs: IpAddress): bool =
## Compares two IpAddresses for Equality. Returns true if the addresses are equal
if lhs.family != rhs.family: return false
@ -1547,7 +1553,7 @@ proc dial*(address: string, port: Port,
# network system problem (e.g. not enough FDs), and not an unreachable
# address.
let err = osLastError()
freeAddrInfo(aiList)
freeaddrinfo(aiList)
closeUnusedFds()
raiseOSError(err)
fdPerDomain[ord(domain)] = lastFd
@ -1556,7 +1562,7 @@ proc dial*(address: string, port: Port,
break
lastError = osLastError()
it = it.ai_next
freeAddrInfo(aiList)
freeaddrinfo(aiList)
closeUnusedFds(ord(domain))
if success:
@ -1586,7 +1592,7 @@ proc connect*(socket: Socket, address: string,
else: lastError = osLastError()
it = it.ai_next
freeAddrInfo(aiList)
freeaddrinfo(aiList)
if not success: raiseOSError(lastError)
when defineSsl:
@ -1634,7 +1640,7 @@ proc connectAsync(socket: Socket, name: string, port = Port(0),
it = it.ai_next
freeAddrInfo(aiList)
freeaddrinfo(aiList)
if not success: raiseOSError(lastError)
proc connect*(socket: Socket, address: string, port = Port(0),

View file

@ -934,13 +934,13 @@ when defined(windows) and not weirdTarget:
template getCommandLine(): untyped = getCommandLineW()
template getFilename(f: untyped): untyped =
$cast[WideCString](addr(f.cFilename[0]))
$cast[WideCString](addr(f.cFileName[0]))
else:
template findFirstFile(a, b: untyped): untyped = findFirstFileA(a, b)
template findNextFile(a, b: untyped): untyped = findNextFileA(a, b)
template getCommandLine(): untyped = getCommandLineA()
template getFilename(f: untyped): untyped = $f.cFilename
template getFilename(f: untyped): untyped = $f.cFileName
proc skipFindData(f: WIN32_FIND_DATA): bool {.inline.} =
# Note - takes advantage of null delimiter in the cstring
@ -1035,7 +1035,7 @@ const
when defined(windows): ["exe", "cmd", "bat"] else: [""]
proc findExe*(exe: string, followSymlinks: bool = true;
extensions: openarray[string]=ExeExts): string {.
extensions: openArray[string]=ExeExts): string {.
tags: [ReadDirEffect, ReadEnvEffect, ReadIOEffect], noNimScript.} =
## Searches for `exe` in the current working directory and then
## in directories listed in the ``PATH`` environment variable.
@ -2867,7 +2867,7 @@ template rawToFormalFileInfo(rawInfo, path, formalInfo): untyped =
formalInfo.permissions.incl(formalMode)
formalInfo.id = (rawInfo.st_dev, rawInfo.st_ino)
formalInfo.size = rawInfo.st_size
formalInfo.linkCount = rawInfo.st_Nlink.BiggestInt
formalInfo.linkCount = rawInfo.st_nlink.BiggestInt
formalInfo.lastAccessTime = rawInfo.st_atim.toTime
formalInfo.lastWriteTime = rawInfo.st_mtim.toTime
formalInfo.creationTime = rawInfo.st_ctim.toTime

View file

@ -501,7 +501,7 @@ when defined(Windows) and not defined(useNimRtl):
#var
# O_WRONLY {.importc: "_O_WRONLY", header: "<fcntl.h>".}: int
# O_RDONLY {.importc: "_O_RDONLY", header: "<fcntl.h>".}: int
proc myDup(h: Handle; inherit: WinBool=1): Handle =
proc myDup(h: Handle; inherit: WINBOOL=1): Handle =
let thisProc = getCurrentProcess()
if duplicateHandle(thisProc, h,
thisProc, addr result,0,inherit,
@ -594,11 +594,11 @@ when defined(Windows) and not defined(useNimRtl):
else:
createPipeHandles(he, si.hStdError)
if setHandleInformation(he, DWORD(1), DWORD(0)) == 0'i32:
raiseOsError(osLastError())
raiseOSError(osLastError())
if setHandleInformation(hi, DWORD(1), DWORD(0)) == 0'i32:
raiseOsError(osLastError())
raiseOSError(osLastError())
if setHandleInformation(ho, DWORD(1), DWORD(0)) == 0'i32:
raiseOsError(osLastError())
raiseOSError(osLastError())
else:
createAllPipeHandles(si, hi, ho, he, cast[int](result))
result.inHandle = FileHandle(hi)
@ -1086,10 +1086,10 @@ elif not defined(useNimRtl):
discard close(p.errHandle)
proc suspend(p: Process) =
if kill(p.id, SIGSTOP) != 0'i32: raiseOsError(osLastError())
if kill(p.id, SIGSTOP) != 0'i32: raiseOSError(osLastError())
proc resume(p: Process) =
if kill(p.id, SIGCONT) != 0'i32: raiseOsError(osLastError())
if kill(p.id, SIGCONT) != 0'i32: raiseOSError(osLastError())
proc running(p: Process): bool =
if p.exitFlag:
@ -1111,11 +1111,11 @@ elif not defined(useNimRtl):
proc terminate(p: Process) =
if kill(p.id, SIGTERM) != 0'i32:
raiseOsError(osLastError())
raiseOSError(osLastError())
proc kill(p: Process) =
if kill(p.id, SIGKILL) != 0'i32:
raiseOsError(osLastError())
raiseOSError(osLastError())
when defined(macosx) or defined(freebsd) or defined(netbsd) or
defined(openbsd) or defined(dragonfly):

View file

@ -505,7 +505,7 @@ proc formatValue*(result: var string; value: string; specifier: string) =
"invalid type in format string for string, expected 's', but got " &
spec.typ)
if spec.precision != -1:
if spec.precision < runelen(value):
if spec.precision < runeLen(value):
setLen(value, runeOffset(value, spec.precision))
result.add alignString(value, spec.minimumWidth, spec.align, spec.fill)

View file

@ -115,7 +115,7 @@ const
IdentStartChars* = {'a'..'z', 'A'..'Z', '_'}
## the set of characters an identifier can start with
NewLines* = {'\13', '\10'}
Newlines* = {'\13', '\10'}
## the set of characters a newline terminator can start with (carriage
## return, line feed)
@ -2360,7 +2360,7 @@ proc formatBiggestFloat*(f: BiggestFloat, format: FloatFormatMode = ffDefault,
for i in 0 ..< L:
# Depending on the locale either dot or comma is produced,
# but nothing else is possible:
if buf[i] in {'.', ','}: result[i] = decimalsep
if buf[i] in {'.', ','}: result[i] = decimalSep
else: result[i] = buf[i]
when defined(windows):
# VS pre 2015 violates the C standard: "The exponent always contains at
@ -2447,7 +2447,7 @@ proc formatSize*(bytes: int64,
var
xb: int64 = bytes
fbytes: float
last_xb: int64 = bytes
lastXb: int64 = bytes
matchedIndex: int
prefixes: array[9, string]
if prefix == bpColloquial:
@ -2458,11 +2458,11 @@ proc formatSize*(bytes: int64,
# Iterate through prefixes seeing if value will be greater than
# 0 in each case
for index in 1..<prefixes.len:
last_xb = xb
lastXb = xb
xb = bytes div (1'i64 shl (index*10))
matchedIndex = index
if xb == 0:
xb = last_xb
xb = lastXb
matchedIndex = index - 1
break
# xb has the integer number for the latest value; index should be correct
@ -2902,7 +2902,7 @@ proc editDistance*(a, b: string): int {.noSideEffect,
for i in 1 .. len1 - 1:
var char1 = a[i + s - 1]
var char2p: int
var D, x: int
var diff, x: int
var p: int
if i >= len1 - half:
# skip the upper triangle:
@ -2913,33 +2913,33 @@ proc editDistance*(a, b: string): int {.noSideEffect,
inc(p)
inc(char2p)
x = row[p] + 1
D = x
diff = x
if x > c3: x = c3
row[p] = x
inc(p)
else:
p = 1
char2p = 0
D = i
diff = i
x = i
if i <= half + 1:
# skip the lower triangle:
e = len2 + i - half - 2
# main:
while p <= e:
dec(D)
var c3 = D + ord(char1 != b[char2p + s])
dec(diff)
var c3 = diff + ord(char1 != b[char2p + s])
inc(char2p)
inc(x)
if x > c3: x = c3
D = row[p] + 1
if x > D: x = D
diff = row[p] + 1
if x > diff: x = diff
row[p] = x
inc(p)
# lower triangle sentinel:
if i <= half:
dec(D)
var c3 = D + ord(char1 != b[char2p + s])
dec(diff)
var c3 = diff + ord(char1 != b[char2p + s])
inc(x)
if x > c3: x = c3
row[p] = x

View file

@ -91,22 +91,22 @@ when defined(windows):
dwSize: DWORD
bVisible: WINBOOL
proc duplicateHandle(hSourceProcessHandle: HANDLE, hSourceHandle: HANDLE,
hTargetProcessHandle: HANDLE, lpTargetHandle: ptr HANDLE,
proc duplicateHandle(hSourceProcessHandle: Handle, hSourceHandle: Handle,
hTargetProcessHandle: Handle, lpTargetHandle: ptr Handle,
dwDesiredAccess: DWORD, bInheritHandle: WINBOOL,
dwOptions: DWORD): WINBOOL{.stdcall, dynlib: "kernel32",
importc: "DuplicateHandle".}
proc getCurrentProcess(): HANDLE{.stdcall, dynlib: "kernel32",
proc getCurrentProcess(): Handle{.stdcall, dynlib: "kernel32",
importc: "GetCurrentProcess".}
proc getConsoleScreenBufferInfo(hConsoleOutput: HANDLE,
proc getConsoleScreenBufferInfo(hConsoleOutput: Handle,
lpConsoleScreenBufferInfo: ptr CONSOLE_SCREEN_BUFFER_INFO): WINBOOL{.stdcall,
dynlib: "kernel32", importc: "GetConsoleScreenBufferInfo".}
proc getConsoleCursorInfo(hConsoleOutput: HANDLE,
proc getConsoleCursorInfo(hConsoleOutput: Handle,
lpConsoleCursorInfo: ptr CONSOLE_CURSOR_INFO): WINBOOL{.
stdcall, dynlib: "kernel32", importc: "GetConsoleCursorInfo".}
proc setConsoleCursorInfo(hConsoleOutput: HANDLE,
proc setConsoleCursorInfo(hConsoleOutput: Handle,
lpConsoleCursorInfo: ptr CONSOLE_CURSOR_INFO): WINBOOL{.
stdcall, dynlib: "kernel32", importc: "SetConsoleCursorInfo".}
@ -140,21 +140,21 @@ when defined(windows):
if h > 0: return h
return 0
proc setConsoleCursorPosition(hConsoleOutput: HANDLE,
proc setConsoleCursorPosition(hConsoleOutput: Handle,
dwCursorPosition: COORD): WINBOOL{.
stdcall, dynlib: "kernel32", importc: "SetConsoleCursorPosition".}
proc fillConsoleOutputCharacter(hConsoleOutput: Handle, cCharacter: char,
nLength: DWORD, dwWriteCoord: Coord,
nLength: DWORD, dwWriteCoord: COORD,
lpNumberOfCharsWritten: ptr DWORD): WINBOOL{.
stdcall, dynlib: "kernel32", importc: "FillConsoleOutputCharacterA".}
proc fillConsoleOutputAttribute(hConsoleOutput: HANDLE, wAttribute: int16,
proc fillConsoleOutputAttribute(hConsoleOutput: Handle, wAttribute: int16,
nLength: DWORD, dwWriteCoord: COORD,
lpNumberOfAttrsWritten: ptr DWORD): WINBOOL{.
stdcall, dynlib: "kernel32", importc: "FillConsoleOutputAttribute".}
proc setConsoleTextAttribute(hConsoleOutput: HANDLE,
proc setConsoleTextAttribute(hConsoleOutput: Handle,
wAttributes: int16): WINBOOL{.
stdcall, dynlib: "kernel32", importc: "SetConsoleTextAttribute".}
@ -165,7 +165,7 @@ when defined(windows):
stdcall, dynlib: "kernel32", importc: "SetConsoleMode".}
proc getCursorPos(h: Handle): tuple [x,y: int] =
var c: CONSOLESCREENBUFFERINFO
var c: CONSOLE_SCREEN_BUFFER_INFO
if getConsoleScreenBufferInfo(h, addr(c)) == 0:
raiseOSError(osLastError())
return (int(c.dwCursorPosition.X), int(c.dwCursorPosition.Y))
@ -178,7 +178,7 @@ when defined(windows):
raiseOSError(osLastError())
proc getAttributes(h: Handle): int16 =
var c: CONSOLESCREENBUFFERINFO
var c: CONSOLE_SCREEN_BUFFER_INFO
# workaround Windows bugs: try several times
if getConsoleScreenBufferInfo(h, addr(c)) != 0:
return c.wAttributes
@ -207,7 +207,7 @@ else:
proc setRaw(fd: FileHandle, time: cint = TCSAFLUSH) =
var mode: Termios
discard fd.tcgetattr(addr mode)
discard fd.tcGetAttr(addr mode)
mode.c_iflag = mode.c_iflag and not Cflag(BRKINT or ICRNL or INPCK or
ISTRIP or IXON)
mode.c_oflag = mode.c_oflag and not Cflag(OPOST)
@ -215,7 +215,7 @@ else:
mode.c_lflag = mode.c_lflag and not Cflag(ECHO or ICANON or IEXTEN or ISIG)
mode.c_cc[VMIN] = 1.cuchar
mode.c_cc[VTIME] = 0.cuchar
discard fd.tcsetattr(time, addr mode)
discard fd.tcSetAttr(time, addr mode)
proc terminalWidthIoctl*(fds: openArray[int]): int =
## Returns terminal width from first fd that supports the ioctl.
@ -315,7 +315,7 @@ proc setCursorXPos*(f: File, x: int) =
## The y position is not changed.
when defined(windows):
let h = conHandle(f)
var scrbuf: CONSOLESCREENBUFFERINFO
var scrbuf: CONSOLE_SCREEN_BUFFER_INFO
if getConsoleScreenBufferInfo(h, addr(scrbuf)) == 0:
raiseOSError(osLastError())
var origin = scrbuf.dwCursorPosition
@ -332,7 +332,7 @@ when defined(windows):
## **Warning**: This is not supported on UNIX!
when defined(windows):
let h = conHandle(f)
var scrbuf: CONSOLESCREENBUFFERINFO
var scrbuf: CONSOLE_SCREEN_BUFFER_INFO
if getConsoleScreenBufferInfo(h, addr(scrbuf)) == 0:
raiseOSError(osLastError())
var origin = scrbuf.dwCursorPosition
@ -417,7 +417,7 @@ proc eraseLine*(f: File) =
## Erases the entire current line.
when defined(windows):
let h = conHandle(f)
var scrbuf: CONSOLESCREENBUFFERINFO
var scrbuf: CONSOLE_SCREEN_BUFFER_INFO
var numwrote: DWORD
if getConsoleScreenBufferInfo(h, addr(scrbuf)) == 0:
raiseOSError(osLastError())
@ -440,7 +440,7 @@ proc eraseScreen*(f: File) =
## Erases the screen with the background colour and moves the cursor to home.
when defined(windows):
let h = conHandle(f)
var scrbuf: CONSOLESCREENBUFFERINFO
var scrbuf: CONSOLE_SCREEN_BUFFER_INFO
var numwrote: DWORD
var origin: COORD # is inititalized to 0, 0
@ -759,10 +759,10 @@ proc getch*(): char =
else:
let fd = getFileHandle(stdin)
var oldMode: Termios
discard fd.tcgetattr(addr oldMode)
discard fd.tcGetAttr(addr oldMode)
fd.setRaw()
result = stdin.readChar()
discard fd.tcsetattr(TCSADRAIN, addr oldMode)
discard fd.tcSetAttr(TCSADRAIN, addr oldMode)
when defined(windows):
from unicode import toUTF8, Rune, runeLenAt
@ -803,14 +803,14 @@ else:
password.string.setLen(0)
let fd = stdin.getFileHandle()
var cur, old: Termios
discard fd.tcgetattr(cur.addr)
discard fd.tcGetAttr(cur.addr)
old = cur
cur.c_lflag = cur.c_lflag and not Cflag(ECHO)
discard fd.tcsetattr(TCSADRAIN, cur.addr)
discard fd.tcSetAttr(TCSADRAIN, cur.addr)
stdout.write prompt
result = stdin.readLine(password)
stdout.write "\n"
discard fd.tcsetattr(TCSADRAIN, old.addr)
discard fd.tcSetAttr(TCSADRAIN, old.addr)
proc readPasswordFromStdin*(prompt = "password: "): TaintedString =
## Reads a password from stdin without printing it.

View file

@ -222,9 +222,9 @@ elif defined(posix):
type CTime = posix.Time
var
realTimeClockId {.importc: "CLOCK_REALTIME", header: "<time.h>".}: Clockid
realTimeClockId {.importc: "CLOCK_REALTIME", header: "<time.h>".}: ClockId
cpuClockId
{.importc: "CLOCK_THREAD_CPUTIME_ID", header: "<time.h>".}: Clockid
{.importc: "CLOCK_THREAD_CPUTIME_ID", header: "<time.h>".}: ClockId
when not defined(freebsd) and not defined(netbsd) and not defined(openbsd):
var timezone {.importc, header: "<time.h>".}: int
@ -689,7 +689,7 @@ proc getDayOfWeek*(monthday: MonthdayRange, month: Month, year: int): WeekDay
assertValidDate monthday, month, year
# 1970-01-01 is a Thursday, we adjust to the previous Monday
let days = toEpochday(monthday, month, year) - 3
let days = toEpochDay(monthday, month, year) - 3
let weeks = floorDiv(days, 7)
let wd = days - weeks * 7
# The value of d is 0 for a Sunday, 1 for a Monday, 2 for a Tuesday, etc.
@ -930,7 +930,7 @@ proc abs*(a: Duration): Duration =
proc toTime*(dt: DateTime): Time {.tags: [], raises: [], benign.} =
## Converts a ``DateTime`` to a ``Time`` representing the same point in time.
let epochDay = toEpochday(dt.monthday, dt.month, dt.year)
let epochDay = toEpochDay(dt.monthday, dt.month, dt.year)
var seconds = epochDay * secondsInDay
seconds.inc dt.hour * secondsInHour
seconds.inc dt.minute * 60
@ -950,7 +950,7 @@ proc initDateTime(zt: ZonedTime, zone: Timezone): DateTime =
rem = rem - minute * secondsInMin
let second = rem
let (d, m, y) = fromEpochday(epochday)
let (d, m, y) = fromEpochDay(epochday)
DateTime(
year: y,
@ -1011,7 +1011,7 @@ proc zonedTimeFromTime*(zone: Timezone, time: Time): ZonedTime =
## Returns the ``ZonedTime`` for some point in time.
zone.zonedTimeFromTimeImpl(time)
proc zonedTimeFromAdjTime*(zone: TimeZone, adjTime: Time): ZonedTime =
proc zonedTimeFromAdjTime*(zone: Timezone, adjTime: Time): ZonedTime =
## Returns the ``ZonedTime`` for some local time.
##
## Note that the ``Time`` argument does not represent a point in time, it
@ -1047,7 +1047,7 @@ proc inZone*(dt: DateTime, zone: Timezone): DateTime
dt.toTime.inZone(zone)
proc toAdjTime(dt: DateTime): Time =
let epochDay = toEpochday(dt.monthday, dt.month, dt.year)
let epochDay = toEpochDay(dt.monthday, dt.month, dt.year)
var seconds = epochDay * secondsInDay
seconds.inc dt.hour * secondsInHour
seconds.inc dt.minute * secondsInMin
@ -1081,7 +1081,7 @@ when defined(JS):
else:
proc toAdjUnix(tm: Tm): int64 =
let epochDay = toEpochday(tm.tm_mday, (tm.tm_mon + 1).Month,
let epochDay = toEpochDay(tm.tm_mday, (tm.tm_mon + 1).Month,
tm.tm_year.int + 1900)
result = epochDay * secondsInDay
result.inc tm.tm_hour * secondsInHour
@ -1147,7 +1147,7 @@ proc utcTzInfo(time: Time): ZonedTime =
var utcInstance {.threadvar.}: Timezone
var localInstance {.threadvar.}: Timezone
proc utc*(): TimeZone =
proc utc*(): Timezone =
## Get the ``Timezone`` implementation for the UTC timezone.
runnableExamples:
doAssert now().utc.timezone == utc()
@ -1156,7 +1156,7 @@ proc utc*(): TimeZone =
utcInstance = newTimezone("Etc/UTC", utcTzInfo, utcTzInfo)
result = utcInstance
proc local*(): TimeZone =
proc local*(): Timezone =
## Get the ``Timezone`` implementation for the local timezone.
runnableExamples:
doAssert now().timezone == local()
@ -1389,7 +1389,7 @@ proc evaluateInterval(dt: DateTime, interval: TimeInterval):
var curMonth = dt.month
# Subtracting
if months < 0:
for mth in countDown(-1 * months, 1):
for mth in countdown(-1 * months, 1):
if curMonth == mJan:
curMonth = mDec
curYear.dec
@ -2111,7 +2111,7 @@ proc parsePattern(input: string, pattern: FormatPattern, i: var int,
i.inc 1
of tt:
if input.substr(i, i+1).cmpIgnoreCase("AM") == 0:
parsed.amPm = apAM
parsed.amPm = apAm
i.inc 2
elif input.substr(i, i+1).cmpIgnoreCase("PM") == 0:
parsed.amPm = apPm

View file

@ -169,7 +169,7 @@ proc runeAt*(s: string, i: Natural): Rune =
doAssert a.runeAt(3) == "y".runeAt(0)
fastRuneAt(s, i, result, false)
proc validateUTF8*(s: string): int =
proc validateUtf8*(s: string): int =
## Returns the position of the invalid byte in ``s`` if the string ``s`` does
## not hold valid UTF-8 data. Otherwise ``-1`` is returned.
##
@ -211,7 +211,7 @@ template fastToUTF8Copy*(c: Rune, s: var string, pos: int, doInc = true) =
## with an additional amount equal to the byte length of ``c``.
##
## See also:
## * `validateUTF8 proc <#validateUTF8,string>`_
## * `validateUtf8 proc <#validateUtf8,string>`_
## * `toUTF8 proc <#toUTF8,Rune>`_
## * `$ proc <#$,Rune>`_ alias for `toUTF8`
var i = RuneImpl(c)
@ -261,7 +261,7 @@ proc toUTF8*(c: Rune): string {.rtl, extern: "nuc$1".} =
## Converts a rune into its UTF-8 representation.
##
## See also:
## * `validateUTF8 proc <#validateUTF8,string>`_
## * `validateUtf8 proc <#validateUtf8,string>`_
## * `$ proc <#$,Rune>`_ alias for `toUTF8`
## * `utf8 iterator <#utf8.i,string>`_
## * `fastToUTF8Copy template <#fastToUTF8Copy.t,Rune,string,int>`_
@ -287,7 +287,7 @@ proc `$`*(rune: Rune): string =
## An alias for `toUTF8 <#toUTF8,Rune>`_.
##
## See also:
## * `validateUTF8 proc <#validateUTF8,string>`_
## * `validateUtf8 proc <#validateUtf8,string>`_
## * `fastToUTF8Copy template <#fastToUTF8Copy.t,Rune,string,int>`_
rune.toUTF8
@ -487,12 +487,12 @@ proc toLower*(c: Rune): Rune {.rtl, extern: "nuc$1", procvar.} =
## * `toTitle proc <#toTitle,Rune>`_
## * `isLower proc <#isLower,Rune>`_
var c = RuneImpl(c)
var p = binarySearch(c, tolowerRanges, len(tolowerRanges) div 3, 3)
if p >= 0 and c >= tolowerRanges[p] and c <= tolowerRanges[p+1]:
return Rune(c + tolowerRanges[p+2] - 500)
p = binarySearch(c, tolowerSinglets, len(tolowerSinglets) div 2, 2)
if p >= 0 and c == tolowerSinglets[p]:
return Rune(c + tolowerSinglets[p+1] - 500)
var p = binarySearch(c, toLowerRanges, len(toLowerRanges) div 3, 3)
if p >= 0 and c >= toLowerRanges[p] and c <= toLowerRanges[p+1]:
return Rune(c + toLowerRanges[p+2] - 500)
p = binarySearch(c, toLowerSinglets, len(toLowerSinglets) div 2, 2)
if p >= 0 and c == toLowerSinglets[p]:
return Rune(c + toLowerSinglets[p+1] - 500)
return Rune(c)
proc toUpper*(c: Rune): Rune {.rtl, extern: "nuc$1", procvar.} =
@ -505,12 +505,12 @@ proc toUpper*(c: Rune): Rune {.rtl, extern: "nuc$1", procvar.} =
## * `toTitle proc <#toTitle,Rune>`_
## * `isUpper proc <#isUpper,Rune>`_
var c = RuneImpl(c)
var p = binarySearch(c, toupperRanges, len(toupperRanges) div 3, 3)
if p >= 0 and c >= toupperRanges[p] and c <= toupperRanges[p+1]:
return Rune(c + toupperRanges[p+2] - 500)
p = binarySearch(c, toupperSinglets, len(toupperSinglets) div 2, 2)
if p >= 0 and c == toupperSinglets[p]:
return Rune(c + toupperSinglets[p+1] - 500)
var p = binarySearch(c, toUpperRanges, len(toUpperRanges) div 3, 3)
if p >= 0 and c >= toUpperRanges[p] and c <= toUpperRanges[p+1]:
return Rune(c + toUpperRanges[p+2] - 500)
p = binarySearch(c, toUpperSinglets, len(toUpperSinglets) div 2, 2)
if p >= 0 and c == toUpperSinglets[p]:
return Rune(c + toUpperSinglets[p+1] - 500)
return Rune(c)
proc toTitle*(c: Rune): Rune {.rtl, extern: "nuc$1", procvar.} =
@ -537,11 +537,11 @@ proc isLower*(c: Rune): bool {.rtl, extern: "nuc$1", procvar.} =
## * `isTitle proc <#isTitle,Rune>`_
var c = RuneImpl(c)
# Note: toUpperRanges is correct here!
var p = binarySearch(c, toupperRanges, len(toupperRanges) div 3, 3)
if p >= 0 and c >= toupperRanges[p] and c <= toupperRanges[p+1]:
var p = binarySearch(c, toUpperRanges, len(toUpperRanges) div 3, 3)
if p >= 0 and c >= toUpperRanges[p] and c <= toUpperRanges[p+1]:
return true
p = binarySearch(c, toupperSinglets, len(toupperSinglets) div 2, 2)
if p >= 0 and c == toupperSinglets[p]:
p = binarySearch(c, toUpperSinglets, len(toUpperSinglets) div 2, 2)
if p >= 0 and c == toUpperSinglets[p]:
return true
proc isUpper*(c: Rune): bool {.rtl, extern: "nuc$1", procvar.} =
@ -557,11 +557,11 @@ proc isUpper*(c: Rune): bool {.rtl, extern: "nuc$1", procvar.} =
## * `isWhiteSpace proc <#isWhiteSpace,Rune>`_
var c = RuneImpl(c)
# Note: toLowerRanges is correct here!
var p = binarySearch(c, tolowerRanges, len(tolowerRanges) div 3, 3)
if p >= 0 and c >= tolowerRanges[p] and c <= tolowerRanges[p+1]:
var p = binarySearch(c, toLowerRanges, len(toLowerRanges) div 3, 3)
if p >= 0 and c >= toLowerRanges[p] and c <= toLowerRanges[p+1]:
return true
p = binarySearch(c, tolowerSinglets, len(tolowerSinglets) div 2, 2)
if p >= 0 and c == tolowerSinglets[p]:
p = binarySearch(c, toLowerSinglets, len(toLowerSinglets) div 2, 2)
if p >= 0 and c == toLowerSinglets[p]:
return true
proc isAlpha*(c: Rune): bool {.rtl, extern: "nuc$1", procvar.} =
@ -805,7 +805,7 @@ iterator utf8*(s: string): string =
## Iterates over any rune of the string ``s`` returning utf8 values.
##
## See also:
## * `validateUTF8 proc <#validateUTF8,string>`_
## * `validateUtf8 proc <#validateUtf8,string>`_
## * `toUTF8 proc <#toUTF8,Rune>`_
## * `$ proc <#$,Rune>`_ alias for `toUTF8`
## * `fastToUTF8Copy template <#fastToUTF8Copy.t,Rune,string,int>`_
@ -928,7 +928,7 @@ proc size*(r: Rune): int {.noSideEffect.} =
else: result = 1
# --------- Private templates for different split separators -----------
proc stringHasSep(s: string, index: int, seps: openarray[Rune]): bool =
proc stringHasSep(s: string, index: int, seps: openArray[Rune]): bool =
var rune: Rune
fastRuneAt(s, index, rune, false)
return seps.contains(rune)
@ -960,7 +960,7 @@ template splitCommon(s, sep, maxsplit: untyped, sepLen: int = -1) =
else:
inc(last, if last < len(s): runeLenAt(s, last) else: 1)
iterator split*(s: string, seps: openarray[Rune] = unicodeSpaces,
iterator split*(s: string, seps: openArray[Rune] = unicodeSpaces,
maxsplit: int = -1): string =
## Splits the unicode string ``s`` into substrings using a group of separators.
##
@ -1044,7 +1044,7 @@ iterator split*(s: string, sep: Rune, maxsplit: int = -1): string =
##
splitCommon(s, sep, maxsplit, sep.size)
proc split*(s: string, seps: openarray[Rune] = unicodeSpaces, maxsplit: int = -1): seq[string] {.
proc split*(s: string, seps: openArray[Rune] = unicodeSpaces, maxsplit: int = -1): seq[string] {.
noSideEffect, rtl, extern: "nucSplitRunes".} =
## The same as the `split iterator <#split.i,string,openArray[Rune],int>`_,
## but is a proc that returns a sequence of substrings.
@ -1057,7 +1057,7 @@ proc split*(s: string, sep: Rune, maxsplit: int = -1): seq[string] {.noSideEffec
accResult(split(s, sep, maxsplit))
proc strip*(s: string, leading = true, trailing = true,
runes: openarray[Rune] = unicodeSpaces): string {.noSideEffect,
runes: openArray[Rune] = unicodeSpaces): string {.noSideEffect,
rtl, extern: "nucStrip".} =
## Strips leading or trailing ``runes`` from ``s`` and returns
## the resulting string.
@ -1072,46 +1072,46 @@ proc strip*(s: string, leading = true, trailing = true,
doAssert a.strip(trailing = false) == "áñyóng "
var
s_i = 0 ## starting index into string ``s``
e_i = len(s) - 1 ## ending index into ``s``, where the last ``Rune`` starts
sI = 0 ## starting index into string ``s``
eI = len(s) - 1 ## ending index into ``s``, where the last ``Rune`` starts
if leading:
var
i = 0
l_i: int ## value of ``s_i`` at the beginning of the iteration
xI: int ## value of ``sI`` at the beginning of the iteration
rune: Rune
while i < len(s):
l_i = i
xI = i
fastRuneAt(s, i, rune)
s_i = i # Assume to start from next rune
sI = i # Assume to start from next rune
if not runes.contains(rune):
s_i = l_i # Go back to where the current rune starts
sI = xI # Go back to where the current rune starts
break
if trailing:
var
i = e_i
l_i: int
i = eI
xI: int
rune: Rune
while i >= 0:
l_i = i
fastRuneAt(s, l_i, rune)
var p_i = i - 1
while p_i >= 0:
xI = i
fastRuneAt(s, xI, rune)
var yI = i - 1
while yI >= 0:
var
p_i_end = p_i
p_rune: Rune
fastRuneAt(s, p_i_end, p_rune)
if p_i_end < l_i: break
i = p_i
rune = p_rune
dec(p_i)
yIend = yI
pRune: Rune
fastRuneAt(s, yIend, pRune)
if yIend < xI: break
i = yI
rune = pRune
dec(yI)
if not runes.contains(rune):
e_i = l_i - 1
eI = xI - 1
break
dec(i)
let newLen = e_i - s_i + 1
let newLen = eI - sI + 1
result = newStringOfCap(newLen)
if newLen > 0:
result.add s[s_i .. e_i]
result.add s[sI .. eI]
proc repeat*(c: Rune, count: Natural): string {.noSideEffect,
rtl, extern: "nucRepeatRune".} =

View file

@ -445,7 +445,7 @@ proc `$`*(u: Uri): string =
result.add(":")
result.add(u.password)
result.add("@")
if u.hostname.endswith('/'):
if u.hostname.endsWith('/'):
result.add(u.hostname[0..^2])
else:
result.add(u.hostname)

View file

@ -462,7 +462,7 @@ proc shallowCopy*[T](x: var T, y: T) {.noSideEffect, magic: "ShallowCopy".}
## and strings.
when defined(nimArrIdx):
# :array|openarray|string|seq|cstring|tuple
# :array|openArray|string|seq|cstring|tuple
proc `[]`*[I: Ordinal;T](a: T; i: I): T {.
noSideEffect, magic: "ArrGet".}
proc `[]=`*[I: Ordinal;T,S](a: T; i: I;
@ -700,7 +700,7 @@ type
## is an `int` type ranging from one to the maximum value
## of an `int`. This type is often useful for documentation and debugging.
RootObj* {.compilerProc, inheritable.} =
RootObj* {.compilerproc, inheritable.} =
object ## The root of Nim's object hierarchy.
##
## Objects should inherit from `RootObj` or one of its descendants.
@ -1026,7 +1026,7 @@ when not defined(JS):
proc len*[TOpenArray: openArray|varargs](x: TOpenArray): int {.
magic: "LengthOpenArray", noSideEffect.}
## Returns the length of an openarray.
## Returns the length of an openArray.
##
## .. code-block:: Nim
## var s = [1, 1, 1, 1, 1]
@ -2002,7 +2002,7 @@ else:
## turned on.
when defined(profiler) and not defined(nimscript):
proc nimProfile() {.compilerProc, noinline.}
proc nimProfile() {.compilerproc, noinline.}
when hasThreadSupport:
{.pragma: rtlThreadVar, threadvar.}
else:
@ -2082,7 +2082,7 @@ const hasAlloc = (hostOS != "standalone" or not defined(nogc)) and not defined(n
when not defined(JS) and not defined(nimscript) and hostOS != "standalone":
include "system/cgprocs"
when not defined(JS) and not defined(nimscript) and hasAlloc and not defined(gcDestructors):
proc addChar(s: NimString, c: char): NimString {.compilerProc, benign.}
proc addChar(s: NimString, c: char): NimString {.compilerproc, benign.}
when not defined(gcDestructors):
proc add*[T](x: var seq[T], y: T) {.magic: "AppendSeqElem", noSideEffect.}
@ -2551,7 +2551,7 @@ proc swap*[T](a, b: var T) {.magic: "Swap", noSideEffect.}
## assert b == 5
when not defined(js) and not defined(booting) and defined(nimTrMacros):
template swapRefsInArray*{swap(arr[a], arr[b])}(arr: openarray[ref], a, b: int) =
template swapRefsInArray*{swap(arr[a], arr[b])}(arr: openArray[ref], a, b: int) =
# Optimize swapping of array elements if they are refs. Default swap
# implementation will cause unsureAsgnRef to be emitted which causes
# unnecessary slow down in this case.
@ -2919,7 +2919,7 @@ proc `==`*[I, T](x, y: array[I, T]): bool =
return
result = true
proc `==`*[T](x, y: openarray[T]): bool =
proc `==`*[T](x, y: openArray[T]): bool =
if x.len != y.len:
return false
@ -2930,7 +2930,7 @@ proc `==`*[T](x, y: openarray[T]): bool =
result = true
proc `@`*[T](a: openArray[T]): seq[T] =
## Turns an *openarray* into a sequence.
## 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`.
@ -3081,9 +3081,9 @@ when not defined(js):
when defined(nimV2):
type
TNimNode {.compilerProc.} = object # to keep the code generator simple
TNimNode {.compilerproc.} = object # to keep the code generator simple
DestructorProc = proc (p: pointer) {.nimcall, benign.}
TNimType {.compilerProc.} = object
TNimType {.compilerproc.} = object
destructor: pointer
size: int
name: cstring
@ -3427,7 +3427,7 @@ template newException*(exceptn: typedesc, message: string;
e
when hostOS == "standalone" and defined(nogc):
proc nimToCStringConv(s: NimString): cstring {.compilerProc, inline.} =
proc nimToCStringConv(s: NimString): cstring {.compilerproc, inline.} =
if s == nil or s.len == 0: result = cstring""
else: result = cstring(addr s.data)
@ -3844,7 +3844,7 @@ elif defined(JS):
return 1
proc quit*(errormsg: string, errorcode = QuitFailure) {.noReturn.} =
proc quit*(errormsg: string, errorcode = QuitFailure) {.noreturn.} =
## A shorthand for ``echo(errormsg); quit(errorcode)``.
when defined(nimscript) or defined(js) or (hostOS == "standalone"):
echo errormsg
@ -4484,21 +4484,21 @@ when defined(windows) and appType == "console" and defined(nimSetUtf8CodePage) a
discard setConsoleOutputCP(65001) # 65001 - utf-8 codepage
when not defined(js):
proc toOpenArray*[T](x: seq[T]; first, last: int): openarray[T] {.
proc toOpenArray*[T](x: seq[T]; first, last: int): openArray[T] {.
magic: "Slice".}
proc toOpenArray*[T](x: openarray[T]; first, last: int): openarray[T] {.
proc toOpenArray*[T](x: openArray[T]; first, last: int): openArray[T] {.
magic: "Slice".}
proc toOpenArray*[T](x: ptr UncheckedArray[T]; first, last: int): openarray[T] {.
proc toOpenArray*[T](x: ptr UncheckedArray[T]; first, last: int): openArray[T] {.
magic: "Slice".}
proc toOpenArray*[I, T](x: array[I, T]; first, last: I): openarray[T] {.
proc toOpenArray*[I, T](x: array[I, T]; first, last: I): openArray[T] {.
magic: "Slice".}
proc toOpenArray*(x: string; first, last: int): openarray[char] {.
proc toOpenArray*(x: string; first, last: int): openArray[char] {.
magic: "Slice".}
proc toOpenArrayByte*(x: string; first, last: int): openarray[byte] {.
proc toOpenArrayByte*(x: string; first, last: int): openArray[byte] {.
magic: "Slice".}
type
ForLoopStmt* {.compilerProc.} = object ## \
ForLoopStmt* {.compilerproc.} = object ## \
## A special type that marks a macro as a `for-loop macro`:idx:.
## See `"For Loop Macro" <manual.html#macros-for-loop-macro>`_.

View file

@ -1007,7 +1007,7 @@ template instantiateForRegion(allocator: untyped) =
dealloc(allocator, p)
proc realloc(p: pointer, newsize: Natural): pointer =
result = realloc(allocator, p, newSize)
result = realloc(allocator, p, newsize)
when false:
proc countFreeMem(): int =
@ -1060,7 +1060,7 @@ template instantiateForRegion(allocator: untyped) =
result = realloc(sharedHeap, p, newsize)
releaseSys(heapLock)
else:
result = realloc(p, newSize)
result = realloc(p, newsize)
when hasThreadSupport:
template sharedMemStatsShared(v: int) =

View file

@ -113,7 +113,7 @@ proc c_signal*(sign: cint, handler: proc (a: cint) {.noconv.}): CSighandlerT {.
type
CFile {.importc: "FILE", header: "<stdio.h>",
incompletestruct.} = object
incompleteStruct.} = object
CFilePtr* = ptr CFile ## The type representing a file handle.
var
@ -142,7 +142,7 @@ proc c_realloc*(p: pointer, newsize: csize): pointer {.
proc c_fwrite*(buf: pointer, size, n: csize, f: CFilePtr): cint {.
importc: "fwrite", header: "<stdio.h>".}
proc rawWrite*(f: CFilePtr, s: cstring) {.compilerproc, nonreloadable, inline.} =
proc rawWrite*(f: CFilePtr, s: cstring) {.compilerproc, nonReloadable, inline.} =
# we cannot throw an exception here!
discard c_fwrite(s, 1, s.len, f)

View file

@ -59,11 +59,11 @@ when defined(builtinOverflow):
proc mulIntOverflow(a, b: int, c: var int): bool {.
importc: "__builtin_smul_overflow", nodecl, nosideeffect.}
proc addInt64(a, b: int64): int64 {.compilerProc, inline.} =
proc addInt64(a, b: int64): int64 {.compilerproc, inline.} =
if addInt64Overflow(a, b, result):
raiseOverflow()
proc subInt64(a, b: int64): int64 {.compilerProc, inline.} =
proc subInt64(a, b: int64): int64 {.compilerproc, inline.} =
if subInt64Overflow(a, b, result):
raiseOverflow()
@ -71,13 +71,13 @@ when defined(builtinOverflow):
if mulInt64Overflow(a, b, result):
raiseOverflow()
else:
proc addInt64(a, b: int64): int64 {.compilerProc, inline.} =
proc addInt64(a, b: int64): int64 {.compilerproc, inline.} =
result = a +% b
if (result xor a) >= int64(0) or (result xor b) >= int64(0):
return result
raiseOverflow()
proc subInt64(a, b: int64): int64 {.compilerProc, inline.} =
proc subInt64(a, b: int64): int64 {.compilerproc, inline.} =
result = a -% b
if (result xor a) >= int64(0) or (result xor not b) >= int64(0):
return result
@ -126,29 +126,29 @@ else:
return result
raiseOverflow()
proc negInt64(a: int64): int64 {.compilerProc, inline.} =
proc negInt64(a: int64): int64 {.compilerproc, inline.} =
if a != low(int64): return -a
raiseOverflow()
proc absInt64(a: int64): int64 {.compilerProc, inline.} =
proc absInt64(a: int64): int64 {.compilerproc, inline.} =
if a != low(int64):
if a >= 0: return a
else: return -a
raiseOverflow()
proc divInt64(a, b: int64): int64 {.compilerProc, inline.} =
proc divInt64(a, b: int64): int64 {.compilerproc, inline.} =
if b == int64(0):
raiseDivByZero()
if a == low(int64) and b == int64(-1):
raiseOverflow()
return a div b
proc modInt64(a, b: int64): int64 {.compilerProc, inline.} =
proc modInt64(a, b: int64): int64 {.compilerproc, inline.} =
if b == int64(0):
raiseDivByZero()
return a mod b
proc absInt(a: int): int {.compilerProc, inline.} =
proc absInt(a: int): int {.compilerproc, inline.} =
if a != low(int):
if a >= 0: return a
else: return -a
@ -164,7 +164,7 @@ const
when asmVersion and not defined(gcc) and not defined(llvm_gcc):
# assembler optimized versions for compilers that
# have an intel syntax assembler:
proc addInt(a, b: int): int {.compilerProc, asmNoStackFrame.} =
proc addInt(a, b: int): int {.compilerproc, asmNoStackFrame.} =
# a in eax, and b in edx
asm """
mov eax, ecx
@ -175,7 +175,7 @@ when asmVersion and not defined(gcc) and not defined(llvm_gcc):
ret
"""
proc subInt(a, b: int): int {.compilerProc, asmNoStackFrame.} =
proc subInt(a, b: int): int {.compilerproc, asmNoStackFrame.} =
asm """
mov eax, ecx
sub eax, edx
@ -185,7 +185,7 @@ when asmVersion and not defined(gcc) and not defined(llvm_gcc):
ret
"""
proc negInt(a: int): int {.compilerProc, asmNoStackFrame.} =
proc negInt(a: int): int {.compilerproc, asmNoStackFrame.} =
asm """
mov eax, ecx
neg eax
@ -195,7 +195,7 @@ when asmVersion and not defined(gcc) and not defined(llvm_gcc):
ret
"""
proc divInt(a, b: int): int {.compilerProc, asmNoStackFrame.} =
proc divInt(a, b: int): int {.compilerproc, asmNoStackFrame.} =
asm """
test edx, edx
jne L_NOT_ZERO
@ -214,7 +214,7 @@ when asmVersion and not defined(gcc) and not defined(llvm_gcc):
ret
"""
proc modInt(a, b: int): int {.compilerProc, asmNoStackFrame.} =
proc modInt(a, b: int): int {.compilerproc, asmNoStackFrame.} =
asm """
test edx, edx
jne L_NOT_ZERO
@ -234,7 +234,7 @@ when asmVersion and not defined(gcc) and not defined(llvm_gcc):
ret
"""
proc mulInt(a, b: int): int {.compilerProc, asmNoStackFrame.} =
proc mulInt(a, b: int): int {.compilerproc, asmNoStackFrame.} =
asm """
mov eax, ecx
mov ecx, edx
@ -247,7 +247,7 @@ when asmVersion and not defined(gcc) and not defined(llvm_gcc):
"""
elif false: # asmVersion and (defined(gcc) or defined(llvm_gcc)):
proc addInt(a, b: int): int {.compilerProc, inline.} =
proc addInt(a, b: int): int {.compilerproc, inline.} =
# don't use a pure proc here!
asm """
"addl %%ecx, %%eax\n"
@ -261,7 +261,7 @@ elif false: # asmVersion and (defined(gcc) or defined(llvm_gcc)):
#/* Intel syntax here */
#".att_syntax"
proc subInt(a, b: int): int {.compilerProc, inline.} =
proc subInt(a, b: int): int {.compilerproc, inline.} =
asm """ "subl %%ecx,%%eax\n"
"jno 1\n"
"call _raiseOverflow\n"
@ -270,7 +270,7 @@ elif false: # asmVersion and (defined(gcc) or defined(llvm_gcc)):
:"a"(`a`), "c"(`b`)
"""
proc mulInt(a, b: int): int {.compilerProc, inline.} =
proc mulInt(a, b: int): int {.compilerproc, inline.} =
asm """ "xorl %%edx, %%edx\n"
"imull %%ecx\n"
"jno 1\n"
@ -281,7 +281,7 @@ elif false: # asmVersion and (defined(gcc) or defined(llvm_gcc)):
:"%edx"
"""
proc negInt(a: int): int {.compilerProc, inline.} =
proc negInt(a: int): int {.compilerproc, inline.} =
asm """ "negl %%eax\n"
"jno 1\n"
"call _raiseOverflow\n"
@ -290,7 +290,7 @@ elif false: # asmVersion and (defined(gcc) or defined(llvm_gcc)):
:"a"(`a`)
"""
proc divInt(a, b: int): int {.compilerProc, inline.} =
proc divInt(a, b: int): int {.compilerproc, inline.} =
asm """ "xorl %%edx, %%edx\n"
"idivl %%ecx\n"
"jno 1\n"
@ -301,7 +301,7 @@ elif false: # asmVersion and (defined(gcc) or defined(llvm_gcc)):
:"%edx"
"""
proc modInt(a, b: int): int {.compilerProc, inline.} =
proc modInt(a, b: int): int {.compilerproc, inline.} =
asm """ "xorl %%edx, %%edx\n"
"idivl %%ecx\n"
"jno 1\n"
@ -314,42 +314,42 @@ elif false: # asmVersion and (defined(gcc) or defined(llvm_gcc)):
"""
when not declared(addInt) and defined(builtinOverflow):
proc addInt(a, b: int): int {.compilerProc, inline.} =
proc addInt(a, b: int): int {.compilerproc, inline.} =
if addIntOverflow(a, b, result):
raiseOverflow()
when not declared(subInt) and defined(builtinOverflow):
proc subInt(a, b: int): int {.compilerProc, inline.} =
proc subInt(a, b: int): int {.compilerproc, inline.} =
if subIntOverflow(a, b, result):
raiseOverflow()
when not declared(mulInt) and defined(builtinOverflow):
proc mulInt(a, b: int): int {.compilerProc, inline.} =
proc mulInt(a, b: int): int {.compilerproc, inline.} =
if mulIntOverflow(a, b, result):
raiseOverflow()
# Platform independent versions of the above (slower!)
when not declared(addInt):
proc addInt(a, b: int): int {.compilerProc, inline.} =
proc addInt(a, b: int): int {.compilerproc, inline.} =
result = a +% b
if (result xor a) >= 0 or (result xor b) >= 0:
return result
raiseOverflow()
when not declared(subInt):
proc subInt(a, b: int): int {.compilerProc, inline.} =
proc subInt(a, b: int): int {.compilerproc, inline.} =
result = a -% b
if (result xor a) >= 0 or (result xor not b) >= 0:
return result
raiseOverflow()
when not declared(negInt):
proc negInt(a: int): int {.compilerProc, inline.} =
proc negInt(a: int): int {.compilerproc, inline.} =
if a != low(int): return -a
raiseOverflow()
when not declared(divInt):
proc divInt(a, b: int): int {.compilerProc, inline.} =
proc divInt(a, b: int): int {.compilerproc, inline.} =
if b == 0:
raiseDivByZero()
if a == low(int) and b == -1:
@ -357,7 +357,7 @@ when not declared(divInt):
return a div b
when not declared(modInt):
proc modInt(a, b: int): int {.compilerProc, inline.} =
proc modInt(a, b: int): int {.compilerproc, inline.} =
if b == 0:
raiseDivByZero()
return a mod b
@ -383,7 +383,7 @@ when not declared(mulInt):
# the only one that can lose catastrophic amounts of information, it's the
# native int product that must have overflowed.
#
proc mulInt(a, b: int): int {.compilerProc.} =
proc mulInt(a, b: int): int {.compilerproc.} =
var
resAsFloat, floatProd: float
@ -412,7 +412,7 @@ when not declared(mulInt):
proc raiseFloatInvalidOp {.noinline.} =
sysFatal(FloatInvalidOpError, "FPU operation caused a NaN result")
proc nanCheck(x: float64) {.compilerProc, inline.} =
proc nanCheck(x: float64) {.compilerproc, inline.} =
if x != x: raiseFloatInvalidOp()
proc raiseFloatOverflow(x: float64) {.noinline.} =
@ -421,5 +421,5 @@ proc raiseFloatOverflow(x: float64) {.noinline.} =
else:
sysFatal(FloatUnderflowError, "FPU operations caused an underflow")
proc infCheck(x: float64) {.compilerProc, inline.} =
proc infCheck(x: float64) {.compilerproc, inline.} =
if x != 0.0 and x*0.5 == x: raiseFloatOverflow(x)

View file

@ -11,12 +11,12 @@ proc `$`(x: int): string {.magic: "IntToStr", noSideEffect.}
proc `$`(info: InstantiationInfo): string =
# The +1 is needed here
# instead of overriding `$` (and changing its meaning), consider explicit name.
info.fileName & "(" & $info.line & ", " & $(info.column+1) & ")"
info.filename & "(" & $info.line & ", " & $(info.column+1) & ")"
# ---------------------------------------------------------------------------
proc raiseAssert*(msg: string) {.noinline, noReturn.} =
proc raiseAssert*(msg: string) {.noinline, noreturn.} =
sysFatal(AssertionError, msg)
proc failedAssertImpl*(msg: string) {.raises: [], tags: [].} =

View file

@ -107,10 +107,10 @@ proc genericAssignAux(dest, src: pointer, mt: PNimType, shallow: bool) =
else:
copyMem(dest, src, mt.size) # copy raw bits
proc genericAssign(dest, src: pointer, mt: PNimType) {.compilerProc.} =
proc genericAssign(dest, src: pointer, mt: PNimType) {.compilerproc.} =
genericAssignAux(dest, src, mt, false)
proc genericShallowAssign(dest, src: pointer, mt: PNimType) {.compilerProc.} =
proc genericShallowAssign(dest, src: pointer, mt: PNimType) {.compilerproc.} =
genericAssignAux(dest, src, mt, true)
when false:
@ -142,7 +142,7 @@ when false:
cprintf("%s %ld\n", k, t.size)
debugNimType(t.base)
proc genericSeqAssign(dest, src: pointer, mt: PNimType) {.compilerProc.} =
proc genericSeqAssign(dest, src: pointer, mt: PNimType) {.compilerproc.} =
var src = src # ugly, but I like to stress the parser sometimes :-)
genericAssign(dest, addr(src), mt)
@ -155,7 +155,7 @@ proc genericAssignOpenArray(dest, src: pointer, len: int,
genericAssign(cast[pointer](d +% i *% mt.base.size),
cast[pointer](s +% i *% mt.base.size), mt.base)
proc objectInit(dest: pointer, typ: PNimType) {.compilerProc, benign.}
proc objectInit(dest: pointer, typ: PNimType) {.compilerproc, benign.}
proc objectInitAux(dest: pointer, n: ptr TNimNode) {.benign.} =
var d = cast[ByteAddress](dest)
case n.kind
@ -188,7 +188,7 @@ proc objectInit(dest: pointer, typ: PNimType) =
# ---------------------- assign zero -----------------------------------------
proc genericReset(dest: pointer, mt: PNimType) {.compilerProc, benign.}
proc genericReset(dest: pointer, mt: PNimType) {.compilerproc, benign.}
proc genericResetAux(dest: pointer, n: ptr TNimNode) =
var d = cast[ByteAddress](dest)
case n.kind
@ -229,7 +229,7 @@ proc selectBranch(discVal, L: int,
proc FieldDiscriminantCheck(oldDiscVal, newDiscVal: int,
a: ptr array[0x7fff, ptr TNimNode],
L: int) {.compilerProc.} =
L: int) {.compilerproc.} =
let oldBranch = selectBranch(oldDiscVal, L, a)
let newBranch = selectBranch(newDiscVal, L, a)
when defined(nimOldCaseObjects):

View file

@ -154,7 +154,7 @@ proc contains(s: CellSet, cell: PCell): bool =
else:
result = false
proc incl(s: var CellSet, cell: PCell) {.noinline.} =
proc incl(s: var CellSet, cell: PCell) =
var u = cast[uint](cell)
var t = cellSetPut(s, u shr PageShift)
u = (u mod PageSize) div MemAlign

View file

@ -99,7 +99,7 @@ when not defined(nimV2):
return true
proc isObjWithCache(obj, subclass: PNimType;
cache: var ObjCheckCache): bool {.compilerProc, inline.} =
cache: var ObjCheckCache): bool {.compilerproc, inline.} =
if obj == subclass: return true
if obj.base == subclass: return true
if cache[0] == obj: return false
@ -116,6 +116,6 @@ when not defined(nimV2):
return true
when defined(nimV2):
proc nimFieldDiscriminantCheckV2(oldDiscVal, newDiscVal: uint8) {.compilerProc.} =
proc nimFieldDiscriminantCheckV2(oldDiscVal, newDiscVal: uint8) {.compilerproc.} =
if oldDiscVal != newDiscVal:
sysFatal(FieldError, "assignment to discriminant changes object branch")

View file

@ -165,14 +165,14 @@ proc genericDeepCopyAux(dest, src: pointer, mt: PNimType; tab: var PtrTable) =
else:
copyMem(dest, src, mt.size)
proc genericDeepCopy(dest, src: pointer, mt: PNimType) {.compilerProc.} =
proc genericDeepCopy(dest, src: pointer, mt: PNimType) {.compilerproc.} =
GC_disable()
var tab = initPtrTable()
genericDeepCopyAux(dest, src, mt, tab)
deinit tab
GC_enable()
proc genericSeqDeepCopy(dest, src: pointer, mt: PNimType) {.compilerProc.} =
proc genericSeqDeepCopy(dest, src: pointer, mt: PNimType) {.compilerproc.} =
# also invoked for 'string'
var src = src
genericDeepCopy(dest, addr(src), mt)

View file

@ -149,7 +149,7 @@ when not defined(nimNoArrayToString):
## Generic ``$`` operator for arrays that is lifted from the components.
collectionToString(x, "[", ", ", "]")
proc `$`*[T](x: openarray[T]): string =
proc `$`*[T](x: openArray[T]): string =
## Generic ``$`` operator for openarrays that is lifted from the components
## of `x`. Example:
##

View file

@ -14,7 +14,7 @@ elif defined(nimQuirky) and not defined(nimscript):
proc name(t: typedesc): string {.magic: "TypeTrait".}
proc sysFatal(exceptn: typedesc, message, arg: string) {.inline, noReturn.} =
proc sysFatal(exceptn: typedesc, message, arg: string) {.inline, noreturn.} =
var buf = newStringOfCap(200)
add(buf, "Error: unhandled exception: ")
add(buf, message)
@ -25,11 +25,11 @@ elif defined(nimQuirky) and not defined(nimscript):
cstderr.rawWrite buf
quit 1
proc sysFatal(exceptn: typedesc, message: string) {.inline, noReturn.} =
proc sysFatal(exceptn: typedesc, message: string) {.inline, noreturn.} =
sysFatal(exceptn, message, "")
else:
proc sysFatal(exceptn: typedesc, message: string) {.inline, noReturn.} =
proc sysFatal(exceptn: typedesc, message: string) {.inline, noreturn.} =
when declared(owned):
var e: owned(ref exceptn)
else:
@ -38,7 +38,7 @@ else:
e.msg = message
raise e
proc sysFatal(exceptn: typedesc, message, arg: string) {.inline, noReturn.} =
proc sysFatal(exceptn: typedesc, message, arg: string) {.inline, noreturn.} =
when declared(owned):
var e: owned(ref exceptn)
else:

View file

@ -184,7 +184,7 @@ proc incRef(c: PCell) {.inline.} =
# and not colorMask
logCell("incRef", c)
proc nimGCref(p: pointer) {.compilerProc.} =
proc nimGCref(p: pointer) {.compilerproc.} =
# we keep it from being collected by pretending it's not even allocated:
let c = usrToCell(p)
add(gch.additionalRoots, c)
@ -202,7 +202,7 @@ proc decRef(c: PCell) {.inline.} =
rtlAddZCT(c)
logCell("decRef", c)
proc nimGCunref(p: pointer) {.compilerProc.} =
proc nimGCunref(p: pointer) {.compilerproc.} =
let cell = usrToCell(p)
var L = gch.additionalRoots.len-1
var i = L
@ -223,15 +223,15 @@ template beforeDealloc(gch: var GcHeap; c: PCell; msg: typed) =
if gch.decStack.d[i] == c:
sysAssert(false, msg)
proc nimGCunrefNoCycle(p: pointer) {.compilerProc, inline.} =
proc nimGCunrefNoCycle(p: pointer) {.compilerproc, inline.} =
sysAssert(allocInv(gch.region), "begin nimGCunrefNoCycle")
decRef(usrToCell(p))
sysAssert(allocInv(gch.region), "end nimGCunrefNoCycle 5")
proc nimGCunrefRC1(p: pointer) {.compilerProc, inline.} =
proc nimGCunrefRC1(p: pointer) {.compilerproc, inline.} =
decRef(usrToCell(p))
proc asgnRef(dest: PPointer, src: pointer) {.compilerProc, inline.} =
proc asgnRef(dest: PPointer, src: pointer) {.compilerproc, inline.} =
# the code generator calls this proc!
gcAssert(not isOnStack(dest), "asgnRef")
# BUGFIX: first incRef then decRef!
@ -242,7 +242,7 @@ proc asgnRef(dest: PPointer, src: pointer) {.compilerProc, inline.} =
proc asgnRefNoCycle(dest: PPointer, src: pointer) {.compilerproc, inline,
deprecated: "old compiler compat".} = asgnRef(dest, src)
proc unsureAsgnRef(dest: PPointer, src: pointer) {.compilerProc.} =
proc unsureAsgnRef(dest: PPointer, src: pointer) {.compilerproc.} =
# unsureAsgnRef updates the reference counters only if dest is not on the
# stack. It is used by the code generator if it cannot decide wether a
# reference is in the stack or not (this can happen for var parameters).

View file

@ -193,12 +193,12 @@ proc doOperation(p: pointer, op: WalkOp) {.benign.}
proc forAllChildrenAux(dest: pointer, mt: PNimType, op: WalkOp) {.benign.}
# we need the prototype here for debugging purposes
proc nimGCref(p: pointer) {.compilerProc.} =
proc nimGCref(p: pointer) {.compilerproc.} =
let cell = usrToCell(p)
markAsEscaped(cell)
add(gch.additionalRoots, cell)
proc nimGCunref(p: pointer) {.compilerProc.} =
proc nimGCunref(p: pointer) {.compilerproc.} =
let cell = usrToCell(p)
var L = gch.additionalRoots.len-1
var i = L
@ -210,10 +210,10 @@ proc nimGCunref(p: pointer) {.compilerProc.} =
break
dec(i)
proc nimGCunrefNoCycle(p: pointer) {.compilerProc, inline.} =
proc nimGCunrefNoCycle(p: pointer) {.compilerproc, inline.} =
discard "can we do some freeing here?"
proc nimGCunrefRC1(p: pointer) {.compilerProc, inline.} =
proc nimGCunrefRC1(p: pointer) {.compilerproc, inline.} =
discard "can we do some freeing here?"
template markGrey(x: PCell) =
@ -225,7 +225,7 @@ template markGrey(x: PCell) =
x.setColor(rcGrey)
add(gch.greyStack, x)
proc asgnRef(dest: PPointer, src: pointer) {.compilerProc, inline.} =
proc asgnRef(dest: PPointer, src: pointer) {.compilerproc, inline.} =
# the code generator calls this proc!
gcAssert(not isOnStack(dest), "asgnRef")
# BUGFIX: first incRef then decRef!
@ -238,7 +238,7 @@ proc asgnRef(dest: PPointer, src: pointer) {.compilerProc, inline.} =
proc asgnRefNoCycle(dest: PPointer, src: pointer) {.compilerproc, inline,
deprecated: "old compiler compat".} = asgnRef(dest, src)
proc unsureAsgnRef(dest: PPointer, src: pointer) {.compilerProc.} =
proc unsureAsgnRef(dest: PPointer, src: pointer) {.compilerproc.} =
# unsureAsgnRef marks 'src' as grey only if dest is not on the
# stack. It is used by the code generator if it cannot decide wether a
# reference is in the stack or not (this can happen for var parameters).

View file

@ -456,7 +456,7 @@ var
threadLocalMarkers {.exportc.}: array[0..3499, GlobalMarkerProc]
gHeapidGenerator: int
proc nimRegisterGlobalMarker(markerProc: GlobalMarkerProc) {.compilerProc.} =
proc nimRegisterGlobalMarker(markerProc: GlobalMarkerProc) {.compilerproc.} =
if globalMarkersLen <= high(globalMarkers):
globalMarkers[globalMarkersLen] = markerProc
inc globalMarkersLen
@ -464,7 +464,7 @@ proc nimRegisterGlobalMarker(markerProc: GlobalMarkerProc) {.compilerProc.} =
cstderr.rawWrite("[GC] cannot register global variable; too many global variables")
quit 1
proc nimRegisterThreadLocalMarker(markerProc: GlobalMarkerProc) {.compilerProc.} =
proc nimRegisterThreadLocalMarker(markerProc: GlobalMarkerProc) {.compilerproc.} =
if threadLocalMarkersLen <= high(threadLocalMarkers):
threadLocalMarkers[threadLocalMarkersLen] = markerProc
inc threadLocalMarkersLen

View file

@ -162,7 +162,7 @@ when defined(nimGcRefLeak):
var ax: array[10_000, GcStackTrace]
proc nimGCref(p: pointer) {.compilerProc.} =
proc nimGCref(p: pointer) {.compilerproc.} =
# we keep it from being collected by pretending it's not even allocated:
when false:
when withBitvectors: excl(gch.allocated, usrToCell(p))
@ -171,7 +171,7 @@ proc nimGCref(p: pointer) {.compilerProc.} =
captureStackTrace(framePtr, ax[gch.additionalRoots.len])
add(gch.additionalRoots, usrToCell(p))
proc nimGCunref(p: pointer) {.compilerProc.} =
proc nimGCunref(p: pointer) {.compilerproc.} =
let cell = usrToCell(p)
var L = gch.additionalRoots.len-1
var i = L
@ -372,14 +372,14 @@ proc mark(gch: var GcHeap, c: PCell) =
c, c.typ.name)
inc gch.indentation, 2
c.refCount = rcBlack
c.refcount = rcBlack
gcAssert gch.tempStack.len == 0, "stack not empty!"
forAllChildren(c, waMarkPrecise)
while gch.tempStack.len > 0:
dec gch.tempStack.len
var d = gch.tempStack.d[gch.tempStack.len]
if d.refcount == rcWhite:
d.refCount = rcBlack
d.refcount = rcBlack
forAllChildren(d, waMarkPrecise)
when defined(nimTracing):

View file

@ -73,7 +73,7 @@ type
tyVoidHidden
TNimNodeKind = enum nkNone, nkSlot, nkList, nkCase
TNimNode {.compilerProc.} = object
TNimNode {.compilerproc.} = object
kind: TNimNodeKind
offset: int
typ: ptr TNimType
@ -86,7 +86,7 @@ type
ntfAcyclic = 1, # type cannot form a cycle
ntfEnumHole = 2 # enum has holes and thus `$` for them needs the slow
# version
TNimType {.compilerProc.} = object
TNimType {.compilerproc.} = object
size: int
kind: TNimKind
flags: set[TNimTypeFlag]
@ -105,7 +105,7 @@ type
when defined(nimTypeNames):
# Declare this variable only once in system.nim
when declared(ThisIsSystem):
var nimTypeRoot {.compilerProc.}: PNimType
var nimTypeRoot {.compilerproc.}: PNimType
else:
var nimTypeRoot {.importc.}: PNimType

View file

@ -12,7 +12,7 @@ include inclrtl
# ----------------- IO Part ------------------------------------------------
type
CFile {.importc: "FILE", header: "<stdio.h>",
incompletestruct.} = object
incompleteStruct.} = object
File* = ptr CFile ## The type representing a file handle.
FileMode* = enum ## The file mode when opening a file.
@ -420,7 +420,7 @@ when defined(windows) and not defined(useWinAnsi):
result = wfreopen(f, m, stream)
else:
proc fopen(filename, mode: cstring): pointer {.importc: "fopen", noDecl.}
proc fopen(filename, mode: cstring): pointer {.importc: "fopen", nodecl.}
proc freopen(filename, mode: cstring, stream: File): File {.
importc: "freopen", nodecl.}
@ -442,7 +442,7 @@ when defined(posix) and not defined(nimscript):
st_mode: Mode ## Mode of file
filler_2: array[144 - 24 - 4, char]
proc S_ISDIR(m: Mode): bool =
proc modeIsDir(m: Mode): bool =
## Test for a directory.
(m and 0o170000) == 0o40000
@ -454,7 +454,7 @@ when defined(posix) and not defined(nimscript):
header: "<sys/stat.h>", final, pure.} = object ## struct stat
st_mode: Mode ## Mode of file
proc S_ISDIR(m: Mode): bool {.importc, header: "<sys/stat.h>".}
proc modeIsDir(m: Mode): bool {.importc: "S_ISDIR", header: "<sys/stat.h>".}
## Test for a directory.
proc c_fstat(a1: cint, a2: var Stat): cint {.
@ -476,7 +476,7 @@ proc open*(f: var File, filename: string,
# be opened.
var f2 = cast[File](p)
var res: Stat
if c_fstat(getFileHandle(f2), res) >= 0'i32 and S_ISDIR(res.st_mode):
if c_fstat(getFileHandle(f2), res) >= 0'i32 and modeIsDir(res.st_mode):
close(f2)
return false
result = true
@ -550,11 +550,11 @@ when declared(stdout):
var echoLock: SysLock
initSysLock echoLock
proc echoBinSafe(args: openArray[string]) {.compilerProc.} =
proc echoBinSafe(args: openArray[string]) {.compilerproc.} =
# flockfile deadlocks some versions of Android 5.x.x
when not defined(windows) and not defined(android) and not defined(nintendoswitch):
proc flockfile(f: File) {.importc, noDecl.}
proc funlockfile(f: File) {.importc, noDecl.}
proc flockfile(f: File) {.importc, nodecl.}
proc funlockfile(f: File) {.importc, nodecl.}
flockfile(stdout)
when defined(windows) and compileOption("threads"):
acquireSys echoLock

View file

@ -9,7 +9,7 @@
# Compilerprocs for strings that do not depend on the string implementation.
proc cmpStrings(a, b: string): int {.inline, compilerProc.} =
proc cmpStrings(a, b: string): int {.inline, compilerproc.} =
let alen = a.len
let blen = b.len
let minlen = min(alen, blen)
@ -20,7 +20,7 @@ proc cmpStrings(a, b: string): int {.inline, compilerProc.} =
else:
result = alen - blen
proc eqStrings(a, b: string): bool {.inline, compilerProc.} =
proc eqStrings(a, b: string): bool {.inline, compilerproc.} =
let alen = a.len
let blen = b.len
if alen == blen:
@ -135,7 +135,7 @@ const
1e20, 1e21, 1e22]
proc nimParseBiggestFloat(s: string, number: var BiggestFloat,
start = 0): int {.compilerProc.} =
start = 0): int {.compilerproc.} =
# This routine attempt to parse float that can parsed quickly.
# ie whose integer part can fit inside a 53bits integer.
# their real exponent must also be <= 22. If the float doesn't follow

View file

@ -40,7 +40,7 @@ else:
template allocStrNoInit(size: untyped): untyped =
cast[NimString](newObjNoInit(addr(strDesc), size))
proc rawNewStringNoInit(space: int): NimString {.compilerProc.} =
proc rawNewStringNoInit(space: int): NimString {.compilerproc.} =
var s = space
if s < 7: s = 7
result = allocStrNoInit(sizeof(TGenericSeq) + s + 1)
@ -49,7 +49,7 @@ proc rawNewStringNoInit(space: int): NimString {.compilerProc.} =
when defined(gogc):
result.elemSize = 1
proc rawNewString(space: int): NimString {.compilerProc.} =
proc rawNewString(space: int): NimString {.compilerproc.} =
var s = space
if s < 7: s = 7
result = allocStr(sizeof(TGenericSeq) + s + 1)
@ -58,11 +58,11 @@ proc rawNewString(space: int): NimString {.compilerProc.} =
when defined(gogc):
result.elemSize = 1
proc mnewString(len: int): NimString {.compilerProc.} =
proc mnewString(len: int): NimString {.compilerproc.} =
result = rawNewString(len)
result.len = len
proc copyStrLast(s: NimString, start, last: int): NimString {.compilerProc.} =
proc copyStrLast(s: NimString, start, last: int): NimString {.compilerproc.} =
# This is not used by most recent versions of the compiler anymore, but
# required for bootstrapping purposes.
let start = max(start, 0)
@ -76,17 +76,17 @@ proc copyStrLast(s: NimString, start, last: int): NimString {.compilerProc.} =
else:
result = rawNewString(len)
proc copyStr(s: NimString, start: int): NimString {.compilerProc.} =
proc copyStr(s: NimString, start: int): NimString {.compilerproc.} =
# This is not used by most recent versions of the compiler anymore, but
# required for bootstrapping purposes.
if s == nil: return nil
result = copyStrLast(s, start, s.len-1)
proc nimToCStringConv(s: NimString): cstring {.compilerProc, nonReloadable, inline.} =
proc nimToCStringConv(s: NimString): cstring {.compilerproc, nonReloadable, inline.} =
if s == nil or s.len == 0: result = cstring""
else: result = cstring(addr s.data)
proc toNimStr(str: cstring, len: int): NimString {.compilerProc.} =
proc toNimStr(str: cstring, len: int): NimString {.compilerproc.} =
result = rawNewStringNoInit(len)
result.len = len
copyMem(addr(result.data), str, len + 1)
@ -245,7 +245,7 @@ proc setLengthStr(s: NimString, newLen: int): NimString {.compilerRtl.} =
# ----------------- sequences ----------------------------------------------
proc incrSeq(seq: PGenericSeq, elemSize: int): PGenericSeq {.compilerProc.} =
proc incrSeq(seq: PGenericSeq, elemSize: int): PGenericSeq {.compilerproc.} =
# increments the length by one:
# this is needed for supporting ``add``;
#
@ -260,7 +260,7 @@ proc incrSeq(seq: PGenericSeq, elemSize: int): PGenericSeq {.compilerProc.} =
result.reserved = r
inc(result.len)
proc incrSeqV2(seq: PGenericSeq, elemSize: int): PGenericSeq {.compilerProc.} =
proc incrSeqV2(seq: PGenericSeq, elemSize: int): PGenericSeq {.compilerproc.} =
# incrSeq version 2
result = seq
if result.len >= result.space:
@ -272,7 +272,7 @@ proc incrSeqV2(seq: PGenericSeq, elemSize: int): PGenericSeq {.compilerProc.} =
template `+!`(p: pointer, s: int): pointer =
cast[pointer](cast[int](p) +% s)
proc incrSeqV3(s: PGenericSeq, typ: PNimType): PGenericSeq {.compilerProc.} =
proc incrSeqV3(s: PGenericSeq, typ: PNimType): PGenericSeq {.compilerproc.} =
if s == nil:
result = cast[PGenericSeq](newSeq(typ, 1))
result.len = 0

View file

@ -14,8 +14,10 @@
import dynlib
when defined(nimHasStyleChecks):
{.push styleChecks: off.}
{.passC: "-DWIN32_LEAN_AND_MEAN".}
{.passc: "-DWIN32_LEAN_AND_MEAN".}
const
useWinUnicode* = not defined(useWinAnsi)
@ -136,11 +138,11 @@ proc getVersion*(): DWORD {.stdcall, dynlib: "kernel32", importc: "GetVersion".}
proc closeHandle*(hObject: Handle): WINBOOL {.stdcall, dynlib: "kernel32",
importc: "CloseHandle".}
proc readFile*(hFile: Handle, Buffer: pointer, nNumberOfBytesToRead: int32,
proc readFile*(hFile: Handle, buffer: pointer, nNumberOfBytesToRead: int32,
lpNumberOfBytesRead: ptr int32, lpOverlapped: pointer): WINBOOL{.
stdcall, dynlib: "kernel32", importc: "ReadFile".}
proc writeFile*(hFile: Handle, Buffer: pointer, nNumberOfBytesToWrite: int32,
proc writeFile*(hFile: Handle, buffer: pointer, nNumberOfBytesToWrite: int32,
lpNumberOfBytesWritten: ptr int32,
lpOverlapped: pointer): WINBOOL{.
stdcall, dynlib: "kernel32", importc: "WriteFile".}
@ -215,13 +217,13 @@ when useWinUnicode:
proc formatMessageW*(dwFlags: int32, lpSource: pointer,
dwMessageId, dwLanguageId: int32,
lpBuffer: pointer, nSize: int32,
Arguments: pointer): int32 {.
arguments: pointer): int32 {.
importc: "FormatMessageW", stdcall, dynlib: "kernel32".}
else:
proc formatMessageA*(dwFlags: int32, lpSource: pointer,
dwMessageId, dwLanguageId: int32,
lpBuffer: pointer, nSize: int32,
Arguments: pointer): int32 {.
arguments: pointer): int32 {.
importc: "FormatMessageA", stdcall, dynlib: "kernel32".}
proc localFree*(p: pointer) {.
@ -414,13 +416,13 @@ proc sleep*(dwMilliseconds: int32){.stdcall, dynlib: "kernel32",
importc: "Sleep".}
when useWinUnicode:
proc shellExecuteW*(HWND: Handle, lpOperation, lpFile,
proc shellExecuteW*(hwnd: Handle, lpOperation, lpFile,
lpParameters, lpDirectory: WideCString,
nShowCmd: int32): Handle{.
stdcall, dynlib: "shell32.dll", importc: "ShellExecuteW".}
else:
proc shellExecuteA*(HWND: Handle, lpOperation, lpFile,
proc shellExecuteA*(hwnd: Handle, lpOperation, lpFile,
lpParameters, lpDirectory: cstring,
nShowCmd: int32): Handle{.
stdcall, dynlib: "shell32.dll", importc: "ShellExecuteA".}
@ -482,12 +484,6 @@ type
sin6_addr*: In6_addr
sin6_scope_id*: int32 # unsigned
Sockaddr_in6_old* = object
sin6_family*: uint16
sin6_port*: int16 # unsigned
sin6_flowinfo*: int32 # unsigned
sin6_addr*: In6_addr
Sockaddr_storage* {.importc: "SOCKADDR_STORAGE",
header: "winsock2.h".} = object
ss_family*: uint16
@ -707,18 +703,18 @@ const
ERROR_HANDLE_EOF* = 38
ERROR_BAD_ARGUMENTS* = 165
proc duplicateHandle*(hSourceProcessHandle: HANDLE, hSourceHandle: HANDLE,
hTargetProcessHandle: HANDLE,
lpTargetHandle: ptr HANDLE,
proc duplicateHandle*(hSourceProcessHandle: Handle, hSourceHandle: Handle,
hTargetProcessHandle: Handle,
lpTargetHandle: ptr Handle,
dwDesiredAccess: DWORD, bInheritHandle: WINBOOL,
dwOptions: DWORD): WINBOOL{.stdcall, dynlib: "kernel32",
importc: "DuplicateHandle".}
proc setHandleInformation*(hObject: HANDLE, dwMask: DWORD,
proc setHandleInformation*(hObject: Handle, dwMask: DWORD,
dwFlags: DWORD): WINBOOL {.stdcall,
dynlib: "kernel32", importc: "SetHandleInformation".}
proc getCurrentProcess*(): HANDLE{.stdcall, dynlib: "kernel32",
proc getCurrentProcess*(): Handle{.stdcall, dynlib: "kernel32",
importc: "GetCurrentProcess".}
when useWinUnicode:
@ -1004,7 +1000,7 @@ const
type
WAITORTIMERCALLBACK* = proc(para1: pointer, para2: int32): void {.stdcall.}
proc postQueuedCompletionStatus*(CompletionPort: HANDLE,
proc postQueuedCompletionStatus*(CompletionPort: Handle,
dwNumberOfBytesTransferred: DWORD,
dwCompletionKey: ULONG_PTR,
lpOverlapped: pointer): bool
@ -1017,7 +1013,7 @@ proc registerWaitForSingleObject*(phNewWaitObject: ptr Handle, hObject: Handle,
dwFlags: ULONG): bool
{.stdcall, dynlib: "kernel32", importc: "RegisterWaitForSingleObject".}
proc unregisterWait*(WaitHandle: HANDLE): DWORD
proc unregisterWait*(WaitHandle: Handle): DWORD
{.stdcall, dynlib: "kernel32", importc: "UnregisterWait".}
proc openProcess*(dwDesiredAccess: DWORD, bInheritHandle: WINBOOL,
@ -1104,6 +1100,9 @@ proc toFILETIME*(t: int64): FILETIME =
type
LPFILETIME* = ptr FILETIME
proc setFileTime*(hFile: HANDLE, lpCreationTime: LPFILETIME,
proc setFileTime*(hFile: Handle, lpCreationTime: LPFILETIME,
lpLastAccessTime: LPFILETIME, lpLastWriteTime: LPFILETIME): WINBOOL
{.stdcall, dynlib: "kernel32", importc: "SetFileTime".}
when defined(nimHasStyleChecks):
{.pop.} # {.push styleChecks: off.}