case consistency part 1

This commit is contained in:
Araq
2013-12-27 15:48:53 +01:00
parent 9e92455a53
commit 2df9b442c6
88 changed files with 1266 additions and 1144 deletions

View File

@@ -14,13 +14,13 @@
## wanted functionality.
when defined(Windows):
proc ReadLineFromStdin*(prompt: string): TaintedString {.
proc readLineFromStdin*(prompt: string): TaintedString {.
tags: [FReadIO, FWriteIO].} =
## Reads a line from stdin.
stdout.write(prompt)
result = readLine(stdin)
proc ReadLineFromStdin*(prompt: string, line: var TaintedString): bool {.
proc readLineFromStdin*(prompt: string, line: var TaintedString): bool {.
tags: [FReadIO, FWriteIO].} =
## Reads a `line` from stdin. `line` must not be
## ``nil``! May throw an IO exception.
@@ -34,7 +34,7 @@ when defined(Windows):
else:
import readline, history
proc ReadLineFromStdin*(prompt: string): TaintedString {.
proc readLineFromStdin*(prompt: string): TaintedString {.
tags: [FReadIO, FWriteIO].} =
var buffer = readline.readLine(prompt)
if isNil(buffer): quit(0)
@@ -43,7 +43,7 @@ else:
add_history(buffer)
readline.free(buffer)
proc ReadLineFromStdin*(prompt: string, line: var TaintedString): bool {.
proc readLineFromStdin*(prompt: string, line: var TaintedString): bool {.
tags: [FReadIO, FWriteIO].} =
var buffer = readline.readLine(prompt)
if isNil(buffer): quit(0)

View File

@@ -120,11 +120,11 @@ proc renderRstToRst(d: var TRenderContext, n: PRstNode, result: var string) =
let oldLen = result.len
renderRstSons(d, n, result)
let HeadlineLen = result.len - oldLen
let headlineLen = result.len - oldLen
result.add("\n")
result.add(ind)
result.add repeatChar(HeadlineLen, lvlToChar[n.level])
result.add repeatChar(headlineLen, lvlToChar[n.level])
of rnOverline:
result.add("\n")
result.add(ind)

View File

@@ -263,14 +263,14 @@ proc `<-`(a: var TIndexEntry, b: TIndexEntry) =
proc sortIndex(a: var openArray[TIndexEntry]) =
# we use shellsort here; fast and simple
let N = len(a)
let n = len(a)
var h = 1
while true:
h = 3 * h + 1
if h > N: break
if h > n: break
while true:
h = h div 3
for i in countup(h, N - 1):
for i in countup(h, n - 1):
var v: TIndexEntry
v <- a[i]
var j = i

View File

@@ -50,7 +50,7 @@ proc mustRehash(length, counter: int): bool {.inline.} =
proc nextTry(h, maxHash: THash): THash {.inline.} =
result = ((5 * h) + 1) and maxHash
proc IntSetGet(t: TIntSet, key: int): PTrunk =
proc intSetGet(t: TIntSet, key: int): PTrunk =
var h = key and t.max
while t.data[h] != nil:
if t.data[h].key == key:
@@ -58,7 +58,7 @@ proc IntSetGet(t: TIntSet, key: int): PTrunk =
h = nextTry(h, t.max)
result = nil
proc IntSetRawInsert(t: TIntSet, data: var TTrunkSeq, desc: PTrunk) =
proc intSetRawInsert(t: TIntSet, data: var TTrunkSeq, desc: PTrunk) =
var h = desc.key and t.max
while data[h] != nil:
assert(data[h] != desc)
@@ -66,7 +66,7 @@ proc IntSetRawInsert(t: TIntSet, data: var TTrunkSeq, desc: PTrunk) =
assert(data[h] == nil)
data[h] = desc
proc IntSetEnlarge(t: var TIntSet) =
proc intSetEnlarge(t: var TIntSet) =
var n: TTrunkSeq
var oldMax = t.max
t.max = ((t.max + 1) * 2) - 1
@@ -75,7 +75,7 @@ proc IntSetEnlarge(t: var TIntSet) =
if t.data[i] != nil: IntSetRawInsert(t, n, t.data[i])
swap(t.data, n)
proc IntSetPut(t: var TIntSet, key: int): PTrunk =
proc intSetPut(t: var TIntSet, key: int): PTrunk =
var h = key and t.max
while t.data[h] != nil:
if t.data[h].key == key:

View File

@@ -41,19 +41,19 @@ type
proc initSinglyLinkedList*[T](): TSinglyLinkedList[T] =
## creates a new singly linked list that is empty.
nil
discard
proc initDoublyLinkedList*[T](): TDoublyLinkedList[T] =
## creates a new doubly linked list that is empty.
nil
discard
proc initSinglyLinkedRing*[T](): TSinglyLinkedRing[T] =
## creates a new singly linked ring that is empty.
nil
discard
proc initDoublyLinkedRing*[T](): TDoublyLinkedRing[T] =
## creates a new doubly linked ring that is empty.
nil
discard
proc newDoublyLinkedNode*[T](value: T): PDoublyLinkedNode[T] =
## creates a new doubly linked node with the given `value`.

View File

@@ -85,7 +85,7 @@ template rawInsertImpl() {.dirty.} =
data[h].val = val
data[h].slot = seFilled
proc RawGet[A, B](t: TTable[A, B], key: A): int =
proc rawGet[A, B](t: TTable[A, B], key: A): int =
rawGetImpl()
proc `[]`*[A, B](t: TTable[A, B], key: A): B =
@@ -93,13 +93,13 @@ proc `[]`*[A, B](t: TTable[A, B], key: A): B =
## default empty value for the type `B` is returned
## and no exception is raised. One can check with ``hasKey`` whether the key
## exists.
var index = RawGet(t, key)
var index = rawGet(t, key)
if index >= 0: result = t.data[index].val
proc mget*[A, B](t: var TTable[A, B], key: A): var B =
## retrieves the value at ``t[key]``. The value can be modified.
## If `key` is not in `t`, the ``EInvalidKey`` exception is raised.
var index = RawGet(t, key)
var index = rawGet(t, key)
if index >= 0: result = t.data[index].val
else: raise newException(EInvalidKey, "key not found: " & $key)
@@ -107,39 +107,39 @@ proc hasKey*[A, B](t: TTable[A, B], key: A): bool =
## returns true iff `key` is in the table `t`.
result = rawGet(t, key) >= 0
proc RawInsert[A, B](t: var TTable[A, B], data: var TKeyValuePairSeq[A, B],
proc rawInsert[A, B](t: var TTable[A, B], data: var TKeyValuePairSeq[A, B],
key: A, val: B) =
rawInsertImpl()
proc Enlarge[A, B](t: var TTable[A, B]) =
proc enlarge[A, B](t: var TTable[A, B]) =
var n: TKeyValuePairSeq[A, B]
newSeq(n, len(t.data) * growthFactor)
for i in countup(0, high(t.data)):
if t.data[i].slot == seFilled: RawInsert(t, n, t.data[i].key, t.data[i].val)
if t.data[i].slot == seFilled: rawInsert(t, n, t.data[i].key, t.data[i].val)
swap(t.data, n)
template AddImpl() {.dirty.} =
if mustRehash(len(t.data), t.counter): Enlarge(t)
RawInsert(t, t.data, key, val)
template addImpl() {.dirty.} =
if mustRehash(len(t.data), t.counter): enlarge(t)
rawInsert(t, t.data, key, val)
inc(t.counter)
template PutImpl() {.dirty.} =
var index = RawGet(t, key)
template putImpl() {.dirty.} =
var index = rawGet(t, key)
if index >= 0:
t.data[index].val = val
else:
AddImpl()
addImpl()
when false:
# not yet used:
template HasKeyOrPutImpl() {.dirty.} =
var index = RawGet(t, key)
template hasKeyOrPutImpl() {.dirty.} =
var index = rawGet(t, key)
if index >= 0:
t.data[index].val = val
result = true
else:
if mustRehash(len(t.data), t.counter): Enlarge(t)
RawInsert(t, t.data, key, val)
if mustRehash(len(t.data), t.counter): enlarge(t)
rawInsert(t, t.data, key, val)
inc(t.counter)
result = false
@@ -149,11 +149,11 @@ proc `[]=`*[A, B](t: var TTable[A, B], key: A, val: B) =
proc add*[A, B](t: var TTable[A, B], key: A, val: B) =
## puts a new (key, value)-pair into `t` even if ``t[key]`` already exists.
AddImpl()
addImpl()
proc del*[A, B](t: var TTable[A, B], key: A) =
## deletes `key` from hash table `t`.
var index = RawGet(t, key)
var index = rawGet(t, key)
if index >= 0:
t.data[index].slot = seDeleted
dec(t.counter)
@@ -240,7 +240,7 @@ iterator mvalues*[A, B](t: var TOrderedTable[A, B]): var B =
forAllOrderedPairs:
yield t.data[h].val
proc RawGet[A, B](t: TOrderedTable[A, B], key: A): int =
proc rawGet[A, B](t: TOrderedTable[A, B], key: A): int =
rawGetImpl()
proc `[]`*[A, B](t: TOrderedTable[A, B], key: A): B =
@@ -248,13 +248,13 @@ proc `[]`*[A, B](t: TOrderedTable[A, B], key: A): B =
## default empty value for the type `B` is returned
## and no exception is raised. One can check with ``hasKey`` whether the key
## exists.
var index = RawGet(t, key)
var index = rawGet(t, key)
if index >= 0: result = t.data[index].val
proc mget*[A, B](t: var TOrderedTable[A, B], key: A): var B =
## retrieves the value at ``t[key]``. The value can be modified.
## If `key` is not in `t`, the ``EInvalidKey`` exception is raised.
var index = RawGet(t, key)
var index = rawGet(t, key)
if index >= 0: result = t.data[index].val
else: raise newException(EInvalidKey, "key not found: " & $key)
@@ -262,7 +262,7 @@ proc hasKey*[A, B](t: TOrderedTable[A, B], key: A): bool =
## returns true iff `key` is in the table `t`.
result = rawGet(t, key) >= 0
proc RawInsert[A, B](t: var TOrderedTable[A, B],
proc rawInsert[A, B](t: var TOrderedTable[A, B],
data: var TOrderedKeyValuePairSeq[A, B],
key: A, val: B) =
rawInsertImpl()
@@ -271,7 +271,7 @@ proc RawInsert[A, B](t: var TOrderedTable[A, B],
if t.last >= 0: data[t.last].next = h
t.last = h
proc Enlarge[A, B](t: var TOrderedTable[A, B]) =
proc enlarge[A, B](t: var TOrderedTable[A, B]) =
var n: TOrderedKeyValuePairSeq[A, B]
newSeq(n, len(t.data) * growthFactor)
var h = t.first
@@ -280,7 +280,7 @@ proc Enlarge[A, B](t: var TOrderedTable[A, B]) =
while h >= 0:
var nxt = t.data[h].next
if t.data[h].slot == seFilled:
RawInsert(t, n, t.data[h].key, t.data[h].val)
rawInsert(t, n, t.data[h].key, t.data[h].val)
h = nxt
swap(t.data, n)
@@ -290,7 +290,7 @@ proc `[]=`*[A, B](t: var TOrderedTable[A, B], key: A, val: B) =
proc add*[A, B](t: var TOrderedTable[A, B], key: A, val: B) =
## puts a new (key, value)-pair into `t` even if ``t[key]`` already exists.
AddImpl()
addImpl()
proc initOrderedTable*[A, B](initialSize=64): TOrderedTable[A, B] =
## creates a new ordered hash table that is empty.
@@ -398,7 +398,7 @@ iterator mvalues*[A](t: TCountTable[A]): var int =
for h in 0..high(t.data):
if t.data[h].val != 0: yield t.data[h].val
proc RawGet[A](t: TCountTable[A], key: A): int =
proc rawGet[A](t: TCountTable[A], key: A): int =
var h: THash = hash(key) and high(t.data) # start with real hash value
while t.data[h].val != 0:
if t.data[h].key == key: return h
@@ -409,13 +409,13 @@ proc `[]`*[A](t: TCountTable[A], key: A): int =
## retrieves the value at ``t[key]``. If `key` is not in `t`,
## 0 is returned. One can check with ``hasKey`` whether the key
## exists.
var index = RawGet(t, key)
var index = rawGet(t, key)
if index >= 0: result = t.data[index].val
proc mget*[A](t: var TCountTable[A], key: A): var int =
## retrieves the value at ``t[key]``. The value can be modified.
## If `key` is not in `t`, the ``EInvalidKey`` exception is raised.
var index = RawGet(t, key)
var index = rawGet(t, key)
if index >= 0: result = t.data[index].val
else: raise newException(EInvalidKey, "key not found: " & $key)
@@ -423,24 +423,24 @@ proc hasKey*[A](t: TCountTable[A], key: A): bool =
## returns true iff `key` is in the table `t`.
result = rawGet(t, key) >= 0
proc RawInsert[A](t: TCountTable[A], data: var seq[tuple[key: A, val: int]],
proc rawInsert[A](t: TCountTable[A], data: var seq[tuple[key: A, val: int]],
key: A, val: int) =
var h: THash = hash(key) and high(data)
while data[h].val != 0: h = nextTry(h, high(data))
data[h].key = key
data[h].val = val
proc Enlarge[A](t: var TCountTable[A]) =
proc enlarge[A](t: var TCountTable[A]) =
var n: seq[tuple[key: A, val: int]]
newSeq(n, len(t.data) * growthFactor)
for i in countup(0, high(t.data)):
if t.data[i].val != 0: RawInsert(t, n, t.data[i].key, t.data[i].val)
if t.data[i].val != 0: rawInsert(t, n, t.data[i].key, t.data[i].val)
swap(t.data, n)
proc `[]=`*[A](t: var TCountTable[A], key: A, val: int) =
## puts a (key, value)-pair into `t`. `val` has to be positive.
assert val > 0
PutImpl()
putImpl()
proc initCountTable*[A](initialSize=64): TCountTable[A] =
## creates a new count table that is empty.
@@ -467,11 +467,11 @@ proc inc*[A](t: var TCountTable[A], key: A, val = 1) =
if index >= 0:
inc(t.data[index].val, val)
else:
if mustRehash(len(t.data), t.counter): Enlarge(t)
RawInsert(t, t.data, key, val)
if mustRehash(len(t.data), t.counter): enlarge(t)
rawInsert(t, t.data, key, val)
inc(t.counter)
proc Smallest*[A](t: TCountTable[A]): tuple[key: A, val: int] =
proc smallest*[A](t: TCountTable[A]): tuple[key: A, val: int] =
## returns the largest (key,val)-pair. Efficiency: O(n)
assert t.len > 0
var minIdx = 0
@@ -480,7 +480,7 @@ proc Smallest*[A](t: TCountTable[A]): tuple[key: A, val: int] =
result.key = t.data[minIdx].key
result.val = t.data[minIdx].val
proc Largest*[A](t: TCountTable[A]): tuple[key: A, val: int] =
proc largest*[A](t: TCountTable[A]): tuple[key: A, val: int] =
## returns the (key,val)-pair with the largest `val`. Efficiency: O(n)
assert t.len > 0
var maxIdx = 0

View File

@@ -48,11 +48,11 @@ proc getCurrentLine*(L: TBaseLexer, marker: bool = true): string
proc getColNumber*(L: TBaseLexer, pos: int): int
## retrieves the current column.
proc HandleCR*(L: var TBaseLexer, pos: int): int
proc handleCR*(L: var TBaseLexer, pos: int): int
## Call this if you scanned over '\c' in the buffer; it returns the the
## position to continue the scanning from. `pos` must be the position
## of the '\c'.
proc HandleLF*(L: var TBaseLexer, pos: int): int
proc handleLF*(L: var TBaseLexer, pos: int): int
## Call this if you scanned over '\L' in the buffer; it returns the the
## position to continue the scanning from. `pos` must be the position
## of the '\L'.
@@ -66,7 +66,7 @@ proc close(L: var TBaseLexer) =
dealloc(L.buf)
close(L.input)
proc FillBuffer(L: var TBaseLexer) =
proc fillBuffer(L: var TBaseLexer) =
var
charsRead, toCopy, s: int # all are in characters,
# not bytes (in case this
@@ -78,7 +78,7 @@ proc FillBuffer(L: var TBaseLexer) =
toCopy = L.BufLen - L.sentinel - 1
assert(toCopy >= 0)
if toCopy > 0:
MoveMem(L.buf, addr(L.buf[L.sentinel + 1]), toCopy * chrSize)
moveMem(L.buf, addr(L.buf[L.sentinel + 1]), toCopy * chrSize)
# "moveMem" handles overlapping regions
charsRead = readData(L.input, addr(L.buf[toCopy]),
(L.sentinel + 1) * chrSize) div chrSize
@@ -103,7 +103,7 @@ proc FillBuffer(L: var TBaseLexer) =
L.bufLen = L.BufLen * 2
L.buf = cast[cstring](realloc(L.buf, L.bufLen * chrSize))
assert(L.bufLen - oldBuflen == oldBufLen)
charsRead = ReadData(L.input, addr(L.buf[oldBufLen]),
charsRead = readData(L.input, addr(L.buf[oldBufLen]),
oldBufLen * chrSize) div chrSize
if charsRead < oldBufLen:
L.buf[oldBufLen + charsRead] = EndOfFile
@@ -121,19 +121,19 @@ proc fillBaseLexer(L: var TBaseLexer, pos: int): int =
result = 0
L.lineStart = result
proc HandleCR(L: var TBaseLexer, pos: int): int =
proc handleCR(L: var TBaseLexer, pos: int): int =
assert(L.buf[pos] == '\c')
inc(L.linenumber)
result = fillBaseLexer(L, pos)
if L.buf[result] == '\L':
result = fillBaseLexer(L, result)
proc HandleLF(L: var TBaseLexer, pos: int): int =
proc handleLF(L: var TBaseLexer, pos: int): int =
assert(L.buf[pos] == '\L')
inc(L.linenumber)
result = fillBaseLexer(L, pos) #L.lastNL := result-1; // BUGFIX: was: result;
proc skip_UTF_8_BOM(L: var TBaseLexer) =
proc skipUtf8Bom(L: var TBaseLexer) =
if (L.buf[0] == '\xEF') and (L.buf[1] == '\xBB') and (L.buf[2] == '\xBF'):
inc(L.bufpos, 3)
inc(L.lineStart, 3)
@@ -149,7 +149,7 @@ proc open(L: var TBaseLexer, input: PStream, bufLen: int = 8192) =
L.lineStart = 0
L.linenumber = 1 # lines start at 1
fillBuffer(L)
skip_UTF_8_BOM(L)
skipUtf8Bom(L)
proc getColNumber(L: TBaseLexer, pos: int): int =
result = abs(pos - L.lineStart)

View File

@@ -93,11 +93,11 @@ when defined(Nimdoc): # only for proper documentation:
elif defined(macos):
const
curdir* = ':'
pardir* = "::"
dirsep* = ':'
altsep* = dirsep
pathsep* = ','
CurDir* = ':'
ParDir* = "::"
Dirsep* = ':'
Altsep* = dirsep
Pathsep* = ','
FileSystemCaseSensitive* = false
ExeExt* = ""
ScriptExt* = ""
@@ -123,42 +123,42 @@ elif defined(macos):
# grandparent etc.
elif doslike:
const
curdir* = '.'
pardir* = ".."
dirsep* = '\\' # seperator within paths
altsep* = '/'
pathSep* = ';' # seperator between paths
Curdir* = '.'
Pardir* = ".."
Dirsep* = '\\' # seperator within paths
Altsep* = '/'
PathSep* = ';' # seperator between paths
FileSystemCaseSensitive* = false
ExeExt* = "exe"
ScriptExt* = "bat"
DynlibFormat* = "$1.dll"
elif defined(PalmOS) or defined(MorphOS):
const
dirsep* = '/'
altsep* = dirsep
Dirsep* = '/'
Altsep* = dirsep
PathSep* = ';'
pardir* = ".."
Pardir* = ".."
FileSystemCaseSensitive* = false
ExeExt* = ""
ScriptExt* = ""
DynlibFormat* = "$1.prc"
elif defined(RISCOS):
const
dirsep* = '.'
altsep* = '.'
pardir* = ".." # is this correct?
pathSep* = ','
Dirsep* = '.'
Altsep* = '.'
Pardir* = ".." # is this correct?
PathSep* = ','
FileSystemCaseSensitive* = true
ExeExt* = ""
ScriptExt* = ""
DynlibFormat* = "lib$1.so"
else: # UNIX-like operating system
const
curdir* = '.'
pardir* = ".."
dirsep* = '/'
altsep* = dirsep
pathSep* = ':'
Curdir* = '.'
Pardir* = ".."
Dirsep* = '/'
Altsep* = dirsep
PathSep* = ':'
FileSystemCaseSensitive* = true
ExeExt* = ""
ScriptExt* = ""
@@ -186,20 +186,20 @@ proc OSErrorMsg*(): string {.rtl, extern: "nos$1", deprecated.} =
result = ""
when defined(Windows):
var err = GetLastError()
var err = getLastError()
if err != 0'i32:
when useWinUnicode:
var msgbuf: widecstring
if FormatMessageW(0x00000100 or 0x00001000 or 0x00000200,
if formatMessageW(0x00000100 or 0x00001000 or 0x00000200,
nil, err, 0, addr(msgbuf), 0, nil) != 0'i32:
result = $msgbuf
if msgbuf != nil: LocalFree(cast[pointer](msgbuf))
if msgbuf != nil: localFree(cast[pointer](msgbuf))
else:
var msgbuf: cstring
if FormatMessageA(0x00000100 or 0x00001000 or 0x00000200,
if formatMessageA(0x00000100 or 0x00001000 or 0x00000200,
nil, err, 0, addr(msgbuf), 0, nil) != 0'i32:
result = $msgbuf
if msgbuf != nil: LocalFree(msgbuf)
if msgbuf != nil: localFree(msgbuf)
if errno != 0'i32:
result = $os.strerror(errno)
@@ -238,16 +238,16 @@ proc OSErrorMsg*(errorCode: TOSErrorCode): string =
if errorCode != TOSErrorCode(0'i32):
when useWinUnicode:
var msgbuf: widecstring
if FormatMessageW(0x00000100 or 0x00001000 or 0x00000200,
if formatMessageW(0x00000100 or 0x00001000 or 0x00000200,
nil, errorCode.int32, 0, addr(msgbuf), 0, nil) != 0'i32:
result = $msgbuf
if msgbuf != nil: LocalFree(cast[pointer](msgbuf))
if msgbuf != nil: localFree(cast[pointer](msgbuf))
else:
var msgbuf: cstring
if FormatMessageA(0x00000100 or 0x00001000 or 0x00000200,
if formatMessageA(0x00000100 or 0x00001000 or 0x00000200,
nil, errorCode.int32, 0, addr(msgbuf), 0, nil) != 0'i32:
result = $msgbuf
if msgbuf != nil: LocalFree(msgbuf)
if msgbuf != nil: localFree(msgbuf)
else:
if errorCode != TOSErrorCode(0'i32):
result = $os.strerror(errorCode.int32)
@@ -287,7 +287,7 @@ proc OSLastError*(): TOSErrorCode =
result = TOSErrorCode(errno)
{.pop.}
proc UnixToNativePath*(path: string): string {.
proc unixToNativePath*(path: string): string {.
noSideEffect, rtl, extern: "nos$1".} =
## Converts an UNIX-like path to a native one.
##
@@ -340,16 +340,16 @@ when defined(windows):
template wrapBinary(varname, winApiProc, arg, arg2: expr) {.immediate.} =
var varname = winApiProc(newWideCString(arg), arg2)
proc FindFirstFile(a: string, b: var TWIN32_FIND_DATA): THandle =
result = FindFirstFileW(newWideCString(a), b)
template FindNextFile(a, b: expr): expr = FindNextFileW(a, b)
proc findFirstFile(a: string, b: var TWIN32_FIND_DATA): THandle =
result = findFirstFileW(newWideCString(a), b)
template findNextFile(a, b: expr): expr = findNextFileW(a, b)
template getCommandLine(): expr = getCommandLineW()
template getFilename(f: expr): expr =
$cast[WideCString](addr(f.cFilename[0]))
else:
template FindFirstFile(a, b: expr): expr = FindFirstFileA(a, b)
template FindNextFile(a, b: expr): expr = FindNextFileA(a, b)
template findFirstFile(a, b: expr): expr = findFirstFileA(a, b)
template findNextFile(a, b: expr): expr = findNextFileA(a, b)
template getCommandLine(): expr = getCommandLineA()
template getFilename(f: expr): expr = $f.cFilename
@@ -364,9 +364,9 @@ proc existsFile*(filename: string): bool {.rtl, extern: "nos$1",
## Returns true if the file exists, false otherwise.
when defined(windows):
when useWinUnicode:
wrapUnary(a, GetFileAttributesW, filename)
wrapUnary(a, getFileAttributesW, filename)
else:
var a = GetFileAttributesA(filename)
var a = getFileAttributesA(filename)
if a != -1'i32:
result = (a and FILE_ATTRIBUTE_DIRECTORY) == 0'i32
else:
@@ -378,9 +378,9 @@ proc existsDir*(dir: string): bool {.rtl, extern: "nos$1", tags: [FReadDir].} =
## is returned.
when defined(windows):
when useWinUnicode:
wrapUnary(a, GetFileAttributesW, dir)
wrapUnary(a, getFileAttributesW, dir)
else:
var a = GetFileAttributesA(dir)
var a = getFileAttributesA(dir)
if a != -1'i32:
result = (a and FILE_ATTRIBUTE_DIRECTORY) != 0'i32
else:
@@ -395,7 +395,7 @@ proc getLastModificationTime*(file: string): TTime {.rtl, extern: "nos$1".} =
return res.st_mtime
else:
var f: TWIN32_Find_Data
var h = findfirstFile(file, f)
var h = findFirstFile(file, f)
if h == -1'i32: OSError(OSLastError())
result = winTimeToUnixTime(rdFileTime(f.ftLastWriteTime))
findclose(h)
@@ -408,7 +408,7 @@ proc getLastAccessTime*(file: string): TTime {.rtl, extern: "nos$1".} =
return res.st_atime
else:
var f: TWIN32_Find_Data
var h = findfirstFile(file, f)
var h = findFirstFile(file, f)
if h == -1'i32: OSError(OSLastError())
result = winTimeToUnixTime(rdFileTime(f.ftLastAccessTime))
findclose(h)
@@ -421,7 +421,7 @@ proc getCreationTime*(file: string): TTime {.rtl, extern: "nos$1".} =
return res.st_ctime
else:
var f: TWIN32_Find_Data
var h = findfirstFile(file, f)
var h = findFirstFile(file, f)
if h == -1'i32: OSError(OSLastError())
result = winTimeToUnixTime(rdFileTime(f.ftCreationTime))
findclose(h)
@@ -437,12 +437,12 @@ proc getCurrentDir*(): string {.rtl, extern: "nos$1", tags: [].} =
when defined(windows):
when useWinUnicode:
var res = newWideCString("", bufsize)
var L = GetCurrentDirectoryW(bufsize, res)
var L = getCurrentDirectoryW(bufsize, res)
if L == 0'i32: OSError(OSLastError())
result = res$L
else:
result = newString(bufsize)
var L = GetCurrentDirectoryA(bufsize, result)
var L = getCurrentDirectoryA(bufsize, result)
if L == 0'i32: OSError(OSLastError())
setLen(result, L)
else:
@@ -457,10 +457,10 @@ proc setCurrentDir*(newDir: string) {.inline, tags: [].} =
## `newDir` cannot been set.
when defined(Windows):
when useWinUnicode:
if SetCurrentDirectoryW(newWideCString(newDir)) == 0'i32:
if setCurrentDirectoryW(newWideCString(newDir)) == 0'i32:
OSError(OSLastError())
else:
if SetCurrentDirectoryA(newDir) == 0'i32: OSError(OSLastError())
if setCurrentDirectoryA(newDir) == 0'i32: OSError(OSLastError())
else:
if chdir(newDir) != 0'i32: OSError(OSLastError())
@@ -512,7 +512,7 @@ proc joinPath*(parts: varargs[string]): string {.noSideEffect,
result = joinPath(result, parts[i])
proc `/` * (head, tail: string): string {.noSideEffect.} =
## The same as ``JoinPath(head, tail)``
## The same as ``joinPath(head, tail)``
##
## Here are some examples for Unix:
##
@@ -526,7 +526,7 @@ proc `/` * (head, tail: string): string {.noSideEffect.} =
proc splitPath*(path: string): tuple[head, tail: string] {.
noSideEffect, rtl, extern: "nos$1".} =
## Splits a directory into (head, tail), so that
## ``JoinPath(head, tail) == path``.
## ``joinPath(head, tail) == path``.
##
## Examples:
##
@@ -672,14 +672,14 @@ proc expandFilename*(filename: string): string {.rtl, extern: "nos$1",
when useWinUnicode:
var unused: widecstring
var res = newWideCString("", bufsize div 2)
var L = GetFullPathNameW(newWideCString(filename), bufsize, res, unused)
var L = getFullPathNameW(newWideCString(filename), bufsize, res, unused)
if L <= 0'i32 or L >= bufsize:
OSError(OSLastError())
result = res$L
else:
var unused: cstring
result = newString(bufsize)
var L = GetFullPathNameA(filename, bufsize, result, unused)
var L = getFullPathNameA(filename, bufsize, result, unused)
if L <= 0'i32 or L >= bufsize: OSError(OSLastError())
setLen(result, L)
else:
@@ -758,29 +758,29 @@ proc sameFile*(path1, path2: string): bool {.rtl, extern: "nos$1",
when useWinUnicode:
var p1 = newWideCString(path1)
var p2 = newWideCString(path2)
template OpenHandle(path: expr): expr =
CreateFileW(path, 0'i32, FILE_SHARE_DELETE or FILE_SHARE_READ or
template openHandle(path: expr): expr =
createFileW(path, 0'i32, FILE_SHARE_DELETE or FILE_SHARE_READ or
FILE_SHARE_WRITE, nil, OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS or FILE_ATTRIBUTE_NORMAL, 0)
var f1 = OpenHandle(p1)
var f2 = OpenHandle(p2)
var f1 = openHandle(p1)
var f2 = openHandle(p2)
else:
template OpenHandle(path: expr): expr =
CreateFileA(path, 0'i32, FILE_SHARE_DELETE or FILE_SHARE_READ or
template openHandle(path: expr): expr =
createFileA(path, 0'i32, FILE_SHARE_DELETE or FILE_SHARE_READ or
FILE_SHARE_WRITE, nil, OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS or FILE_ATTRIBUTE_NORMAL, 0)
var f1 = OpenHandle(path1)
var f2 = OpenHandle(path2)
var f1 = openHandle(path1)
var f2 = openHandle(path2)
var lastErr: TOSErrorCode
if f1 != INVALID_HANDLE_VALUE and f2 != INVALID_HANDLE_VALUE:
var fi1, fi2: TBY_HANDLE_FILE_INFORMATION
if GetFileInformationByHandle(f1, addr(fi1)) != 0 and
GetFileInformationByHandle(f2, addr(fi2)) != 0:
if getFileInformationByHandle(f1, addr(fi1)) != 0 and
getFileInformationByHandle(f2, addr(fi2)) != 0:
result = fi1.dwVolumeSerialNumber == fi2.dwVolumeSerialNumber and
fi1.nFileIndexHigh == fi2.nFileIndexHigh and
fi1.nFileIndexLow == fi2.nFileIndexLow
@@ -791,8 +791,8 @@ proc sameFile*(path1, path2: string): bool {.rtl, extern: "nos$1",
lastErr = OSLastError()
success = false
discard CloseHandle(f1)
discard CloseHandle(f2)
discard closeHandle(f1)
discard closeHandle(f2)
if not success: OSError(lastErr)
else:
@@ -867,9 +867,9 @@ proc getFilePermissions*(filename: string): set[TFilePermission] {.
if (a.st_mode and S_IXOTH) != 0'i32: result.incl(fpOthersExec)
else:
when useWinUnicode:
wrapUnary(res, GetFileAttributesW, filename)
wrapUnary(res, getFileAttributesW, filename)
else:
var res = GetFileAttributesA(filename)
var res = getFileAttributesA(filename)
if res == -1'i32: OSError(OSLastError())
if (res and FILE_ATTRIBUTE_READONLY) != 0'i32:
result = {fpUserExec, fpUserRead, fpGroupExec, fpGroupRead,
@@ -899,18 +899,18 @@ proc setFilePermissions*(filename: string, permissions: set[TFilePermission]) {.
if chmod(filename, p) != 0: OSError(OSLastError())
else:
when useWinUnicode:
wrapUnary(res, GetFileAttributesW, filename)
wrapUnary(res, getFileAttributesW, filename)
else:
var res = GetFileAttributesA(filename)
var res = getFileAttributesA(filename)
if res == -1'i32: OSError(OSLastError())
if fpUserWrite in permissions:
res = res and not FILE_ATTRIBUTE_READONLY
else:
res = res or FILE_ATTRIBUTE_READONLY
when useWinUnicode:
wrapBinary(res2, SetFileAttributesW, filename, res)
wrapBinary(res2, setFileAttributesW, filename, res)
else:
var res2 = SetFileAttributesA(filename, res)
var res2 = setFileAttributesA(filename, res)
if res2 == - 1'i32: OSError(OSLastError())
proc copyFile*(source, dest: string) {.rtl, extern: "nos$1",
@@ -928,9 +928,9 @@ proc copyFile*(source, dest: string) {.rtl, extern: "nos$1",
when useWinUnicode:
let s = newWideCString(source)
let d = newWideCString(dest)
if CopyFileW(s, d, 0'i32) == 0'i32: OSError(OSLastError())
if copyFileW(s, d, 0'i32) == 0'i32: OSError(OSLastError())
else:
if CopyFileA(source, dest, 0'i32) == 0'i32: OSError(OSLastError())
if copyFileA(source, dest, 0'i32) == 0'i32: OSError(OSLastError())
else:
# generic version of copyFile which works for any platform:
const bufSize = 8000 # better for memory manager
@@ -940,7 +940,7 @@ proc copyFile*(source, dest: string) {.rtl, extern: "nos$1",
close(s)
OSError(OSLastError())
var buf = alloc(bufsize)
while True:
while true:
var bytesread = readBuffer(s, buf, bufsize)
if bytesread > 0:
var byteswritten = writeBuffer(d, buf, bytesread)
@@ -968,13 +968,13 @@ when not defined(ENOENT) and not defined(Windows):
when defined(Windows):
when useWinUnicode:
template DeleteFile(file: expr): expr {.immediate.} = DeleteFileW(file)
template SetFileAttributes(file, attrs: expr): expr {.immediate.} =
SetFileAttributesW(file, attrs)
template deleteFile(file: expr): expr {.immediate.} = deleteFileW(file)
template setFileAttributes(file, attrs: expr): expr {.immediate.} =
setFileAttributesW(file, attrs)
else:
template DeleteFile(file: expr): expr {.immediate.} = DeleteFileA(file)
template SetFileAttributes(file, attrs: expr): expr {.immediate.} =
SetFileAttributesA(file, attrs)
template deleteFile(file: expr): expr {.immediate.} = deleteFileA(file)
template setFileAttributes(file, attrs: expr): expr {.immediate.} =
setFileAttributesA(file, attrs)
proc removeFile*(file: string) {.rtl, extern: "nos$1", tags: [FWriteDir].} =
## Removes the `file`. If this fails, `EOS` is raised. This does not fail
@@ -985,11 +985,11 @@ proc removeFile*(file: string) {.rtl, extern: "nos$1", tags: [FWriteDir].} =
let f = newWideCString(file)
else:
let f = file
if DeleteFile(f) == 0:
if GetLastError() == ERROR_ACCESS_DENIED:
if SetFileAttributes(f, FILE_ATTRIBUTE_NORMAL) == 0:
if deleteFile(f) == 0:
if getLastError() == ERROR_ACCESS_DENIED:
if setFileAttributes(f, FILE_ATTRIBUTE_NORMAL) == 0:
OSError(OSLastError())
if DeleteFile(f) == 0:
if deleteFile(f) == 0:
OSError(OSLastError())
else:
if cremove(file) != 0'i32 and errno != ENOENT:
@@ -1076,7 +1076,7 @@ else:
when useNSGetEnviron:
var gEnv = NSGetEnviron()[]
var i = 0
while True:
while true:
if gEnv[i] == nil: break
add environment, $gEnv[i]
inc(i)
@@ -1130,9 +1130,9 @@ proc putEnv*(key, val: string) {.tags: [FWriteEnv].} =
when useWinUnicode:
var k = newWideCString(key)
var v = newWideCString(val)
if SetEnvironmentVariableW(k, v) == 0'i32: OSError(OSLastError())
if setEnvironmentVariableW(k, v) == 0'i32: OSError(OSLastError())
else:
if SetEnvironmentVariableA(key, val) == 0'i32: OSError(OSLastError())
if setEnvironmentVariableA(key, val) == 0'i32: OSError(OSLastError())
iterator envPairs*(): tuple[key, value: TaintedString] {.tags: [FReadEnv].} =
## Iterate over all `environments variables`:idx:. In the first component
@@ -1259,9 +1259,9 @@ iterator walkDirRec*(dir: string, filter={pcFile, pcDir}): string {.
proc rawRemoveDir(dir: string) =
when defined(windows):
when useWinUnicode:
wrapUnary(res, RemoveDirectoryW, dir)
wrapUnary(res, removeDirectoryW, dir)
else:
var res = RemoveDirectoryA(dir)
var res = removeDirectoryA(dir)
let lastError = OSLastError()
if res == 0'i32 and lastError.int32 != 3'i32 and
lastError.int32 != 18'i32 and lastError.int32 != 2'i32:
@@ -1291,10 +1291,10 @@ proc rawCreateDir(dir: string) =
OSError(OSLastError())
else:
when useWinUnicode:
wrapUnary(res, CreateDirectoryW, dir)
wrapUnary(res, createDirectoryW, dir)
else:
var res = CreateDirectoryA(dir)
if res == 0'i32 and GetLastError() != 183'i32:
var res = createDirectoryA(dir)
if res == 0'i32 and getLastError() != 183'i32:
OSError(OSLastError())
proc createDir*(dir: string) {.rtl, extern: "nos$1", tags: [FWriteDir].} =
@@ -1584,8 +1584,8 @@ proc getAppFilename*(): string {.rtl, extern: "nos$1", tags: [FReadIO].} =
if len(result) > 0 and result[0] != DirSep: # not an absolute path?
# iterate over any path in the $PATH environment variable
for p in split(string(getEnv("PATH")), {PathSep}):
var x = JoinPath(p, result)
if ExistsFile(x): return x
var x = joinPath(p, result)
if existsFile(x): return x
proc getApplicationFilename*(): string {.rtl, extern: "nos$1", deprecated.} =
## Returns the filename of the application's executable.
@@ -1636,11 +1636,11 @@ proc findExe*(exe: string): string {.tags: [FReadDir, FReadEnv].} =
## Returns "" if the `exe` cannot be found. On DOS-like platforms, `exe`
## is added an ``.exe`` file extension if it has no extension.
result = addFileExt(exe, os.exeExt)
if ExistsFile(result): return
if existsFile(result): return
var path = string(os.getEnv("PATH"))
for candidate in split(path, pathSep):
var x = candidate / result
if ExistsFile(x): return x
if existsFile(x): return x
result = ""
proc expandTilde*(path: string): string =

View File

@@ -383,16 +383,16 @@ when defined(Windows) and not defined(useNimRtl):
# O_WRONLY {.importc: "_O_WRONLY", header: "<fcntl.h>".}: int
# O_RDONLY {.importc: "_O_RDONLY", header: "<fcntl.h>".}: int
proc CreatePipeHandles(Rdhandle, WrHandle: var THandle) =
proc createPipeHandles(Rdhandle, WrHandle: var THandle) =
var piInheritablePipe: TSecurityAttributes
piInheritablePipe.nlength = SizeOF(TSecurityAttributes).cint
piInheritablePipe.nlength = SizeOf(TSecurityAttributes).cint
piInheritablePipe.lpSecurityDescriptor = nil
piInheritablePipe.Binherithandle = 1
if CreatePipe(Rdhandle, Wrhandle, piInheritablePipe, 1024) == 0'i32:
if createPipe(Rdhandle, Wrhandle, piInheritablePipe, 1024) == 0'i32:
OSError(OSLastError())
proc fileClose(h: THandle) {.inline.} =
if h > 4: discard CloseHandle(h)
if h > 4: discard closeHandle(h)
proc startProcess(command: string,
workingDir: string = "",
@@ -400,8 +400,8 @@ when defined(Windows) and not defined(useNimRtl):
env: PStringTable = nil,
options: set[TProcessOption] = {poStdErrToStdOut}): PProcess =
var
SI: TStartupInfo
ProcInfo: TProcessInformation
si: TStartupInfo
procInfo: TProcessInformation
success: int
hi, ho, he: THandle
new(result)
@@ -511,8 +511,8 @@ when defined(Windows) and not defined(useNimRtl):
proc execCmd(command: string): int =
var
SI: TStartupInfo
ProcInfo: TProcessInformation
si: TStartupInfo
procInfo: TProcessInformation
process: THandle
L: int32
SI.cb = SizeOf(SI).cint

View File

@@ -51,7 +51,7 @@ proc parseHex*(s: string, number: var int, start = 0): int {.
elif s[i] == '#': inc(i)
while true:
case s[i]
of '_': nil
of '_': discard
of '0'..'9':
number = number shl 4 or (ord(s[i]) - ord('0'))
foundDigit = true
@@ -74,7 +74,7 @@ proc parseOct*(s: string, number: var int, start = 0): int {.
if s[i] == '0' and (s[i+1] == 'o' or s[i+1] == 'O'): inc(i, 2)
while true:
case s[i]
of '_': nil
of '_': discard
of '0'..'7':
number = number shl 3 or (ord(s[i]) - ord('0'))
foundDigit = true

View File

@@ -132,17 +132,17 @@ type
ETimeout* = object of ESynch
let
InvalidSocket*: TSocket = nil ## invalid socket
invalidSocket*: TSocket = nil ## invalid socket
when defined(windows):
let
OSInvalidSocket = winlean.INVALID_SOCKET
osInvalidSocket = winlean.INVALID_SOCKET
else:
let
OSInvalidSocket = posix.INVALID_SOCKET
osInvalidSocket = posix.INVALID_SOCKET
proc newTSocket(fd: TSocketHandle, isBuff: bool): TSocket =
if fd == OSInvalidSocket:
if fd == osInvalidSocket:
return nil
new(result)
result.fd = fd
@@ -187,14 +187,14 @@ proc htons*(x: int16): int16 =
result = sockets.ntohs(x)
when defined(Posix):
proc ToInt(domain: TDomain): cint =
proc toInt(domain: TDomain): cint =
case domain
of AF_UNIX: result = posix.AF_UNIX
of AF_INET: result = posix.AF_INET
of AF_INET6: result = posix.AF_INET6
else: nil
proc ToInt(typ: TType): cint =
proc toInt(typ: TType): cint =
case typ
of SOCK_STREAM: result = posix.SOCK_STREAM
of SOCK_DGRAM: result = posix.SOCK_DGRAM
@@ -202,7 +202,7 @@ when defined(Posix):
of SOCK_RAW: result = posix.SOCK_RAW
else: nil
proc ToInt(p: TProtocol): cint =
proc toInt(p: TProtocol): cint =
case p
of IPPROTO_TCP: result = posix.IPPROTO_TCP
of IPPROTO_UDP: result = posix.IPPROTO_UDP
@@ -216,10 +216,10 @@ else:
proc toInt(domain: TDomain): cint =
result = toU16(ord(domain))
proc ToInt(typ: TType): cint =
proc toInt(typ: TType): cint =
result = cint(ord(typ))
proc ToInt(p: TProtocol): cint =
proc toInt(p: TProtocol): cint =
result = cint(ord(p))
proc socket*(domain: TDomain = AF_INET, typ: TType = SOCK_STREAM,
@@ -333,7 +333,7 @@ when defined(ssl):
if SSLSetFd(socket.sslHandle, socket.fd) != 1:
SSLError()
proc SocketError*(socket: TSocket, err: int = -1, async = false) =
proc socketError*(socket: TSocket, err: int = -1, async = false) =
## Raises proper errors based on return values of ``recv`` functions.
##
## If ``async`` is ``True`` no error will be thrown in the case when the
@@ -471,7 +471,7 @@ template acceptAddrPlain(noClientRet, successRet: expr,
var sock = accept(server.fd, cast[ptr TSockAddr](addr(sockAddress)),
addr(addrLen))
if sock == OSInvalidSocket:
if sock == osInvalidSocket:
let err = OSLastError()
when defined(windows):
if err.int32 == WSAEINPROGRESS:
@@ -1661,7 +1661,7 @@ when defined(Windows):
proc setBlocking(s: TSocket, blocking: bool) =
when defined(Windows):
var mode = clong(ord(not blocking)) # 1 for non-blocking, 0 for blocking
if ioctlsocket(TSocketHandle(s.fd), FIONBIO, addr(mode)) == -1:
if ioctlsocket(s.fd, FIONBIO, addr(mode)) == -1:
OSError(OSLastError())
else: # BSD sockets
var x: int = fcntl(s.fd, F_GETFL, 0)

View File

@@ -88,7 +88,7 @@ proc mustRehash(length, counter: int): bool =
proc nextTry(h, maxHash: THash): THash {.inline.} =
result = ((5 * h) + 1) and maxHash
proc RawGet(t: PStringTable, key: string): int =
proc rawGet(t: PStringTable, key: string): int =
var h: THash = myhash(t, key) and high(t.data) # start with real hash value
while not isNil(t.data[h].key):
if mycmp(t, t.data[h].key, key):
@@ -116,14 +116,14 @@ proc hasKey*(t: PStringTable, key: string): bool {.rtl, extern: "nst$1".} =
## returns true iff `key` is in the table `t`.
result = rawGet(t, key) >= 0
proc RawInsert(t: PStringTable, data: var TKeyValuePairSeq, key, val: string) =
proc rawInsert(t: PStringTable, data: var TKeyValuePairSeq, key, val: string) =
var h: THash = myhash(t, key) and high(data)
while not isNil(data[h].key):
h = nextTry(h, high(data))
data[h].key = key
data[h].val = val
proc Enlarge(t: PStringTable) =
proc enlarge(t: PStringTable) =
var n: TKeyValuePairSeq
newSeq(n, len(t.data) * growthFactor)
for i in countup(0, high(t.data)):
@@ -140,7 +140,7 @@ proc `[]=`*(t: PStringTable, key, val: string) {.rtl, extern: "nstPut".} =
RawInsert(t, t.data, key, val)
inc(t.counter)
proc RaiseFormatException(s: string) =
proc raiseFormatException(s: string) =
var e: ref EInvalidValue
new(e)
e.msg = "format string: key not found: " & s

View File

@@ -128,7 +128,7 @@ proc cmpIgnoreStyle*(a, b: string): int {.noSideEffect,
## | > 0 iff a > b
var i = 0
var j = 0
while True:
while true:
while a[i] == '_': inc(i)
while b[j] == '_': inc(j) # BUGFIX: typo
var aa = toLower(a[i])
@@ -344,7 +344,7 @@ proc intToStr*(x: int, minchars: int = 1): string {.noSideEffect,
if x < 0:
result = '-' & result
proc ParseInt*(s: string): int {.noSideEffect, procvar,
proc parseInt*(s: string): int {.noSideEffect, procvar,
rtl, extern: "nsuParseInt".} =
## Parses a decimal integer value contained in `s`. If `s` is not
## a valid integer, `EInvalidValue` is raised.
@@ -352,7 +352,7 @@ proc ParseInt*(s: string): int {.noSideEffect, procvar,
if L != s.len or L == 0:
raise newException(EInvalidValue, "invalid integer: " & s)
proc ParseBiggestInt*(s: string): biggestInt {.noSideEffect, procvar,
proc parseBiggestInt*(s: string): biggestInt {.noSideEffect, procvar,
rtl, extern: "nsuParseBiggestInt".} =
## Parses a decimal integer value contained in `s`. If `s` is not
## a valid integer, `EInvalidValue` is raised.
@@ -360,7 +360,7 @@ proc ParseBiggestInt*(s: string): biggestInt {.noSideEffect, procvar,
if L != s.len or L == 0:
raise newException(EInvalidValue, "invalid integer: " & s)
proc ParseFloat*(s: string): float {.noSideEffect, procvar,
proc parseFloat*(s: string): float {.noSideEffect, procvar,
rtl, extern: "nsuParseFloat".} =
## Parses a decimal floating point value contained in `s`. If `s` is not
## a valid floating point number, `EInvalidValue` is raised. ``NAN``,
@@ -369,7 +369,7 @@ proc ParseFloat*(s: string): float {.noSideEffect, procvar,
if L != s.len or L == 0:
raise newException(EInvalidValue, "invalid float: " & s)
proc ParseHexInt*(s: string): int {.noSideEffect, procvar,
proc parseHexInt*(s: string): int {.noSideEffect, procvar,
rtl, extern: "nsuParseHexInt".} =
## Parses a hexadecimal integer value contained in `s`. If `s` is not
## a valid integer, `EInvalidValue` is raised. `s` can have one of the
@@ -455,7 +455,7 @@ proc align*(s: string, count: int, padding = ' '): string {.
## assert align("1232", 6, '#') == "##1232"
if s.len < count:
result = newString(count)
var spaces = count - s.len
let spaces = count - s.len
for i in 0..spaces-1: result[i] = padding
for i in spaces..count-1: result[i] = s[i-spaces]
else:
@@ -649,7 +649,7 @@ proc join*(a: openArray[string]): string {.
result = ""
type
TSkipTable = array[Char, int]
TSkipTable = array[char, int]
proc preprocessSub(sub: string, a: var TSkipTable) =
var m = len(sub)
@@ -795,7 +795,7 @@ proc delete*(s: var string, first, last: int) {.noSideEffect,
inc(j)
setlen(s, newLen)
proc ParseOctInt*(s: string): int {.noSideEffect,
proc parseOctInt*(s: string): int {.noSideEffect,
rtl, extern: "nsuParseOctInt".} =
## Parses an octal integer value contained in `s`. If `s` is not
## a valid integer, `EInvalidValue` is raised. `s` can have one of the
@@ -896,7 +896,7 @@ proc unescape*(s: string, prefix = "\"", suffix = "\""): string {.noSideEffect,
raise newException(EInvalidValue,
"String does not start with a prefix of: " & prefix)
i.inc()
while True:
while true:
if i == s.len-suffix.len: break
case s[i]
of '\\':

View File

@@ -146,7 +146,7 @@ proc getGMTime*(t: TTime): TTimeInfo {.tags: [FTime], raises: [].}
## converts the calendar time `t` to broken-down time representation,
## expressed in Coordinated Universal Time (UTC).
proc TimeInfoToTime*(timeInfo: TTimeInfo): TTime {.tags: [].}
proc timeInfoToTime*(timeInfo: TTimeInfo): TTime {.tags: [].}
## converts a broken-down time structure to
## calendar time representation. The function ignores the specified
## contents of the structure members `weekday` and `yearday` and recomputes
@@ -297,7 +297,7 @@ when not defined(JS):
when not defined(JS):
# C wrapper:
type
structTM {.importc: "struct tm", final.} = object
StructTM {.importc: "struct tm", final.} = object
second {.importc: "tm_sec".},
minute {.importc: "tm_min".},
hour {.importc: "tm_hour".},
@@ -308,7 +308,7 @@ when not defined(JS):
yearday {.importc: "tm_yday".},
isdst {.importc: "tm_isdst".}: cint
PTimeInfo = ptr structTM
PTimeInfo = ptr StructTM
PTime = ptr TTime
TClock {.importc: "clock_t".} = distinct int
@@ -401,7 +401,7 @@ when not defined(JS):
# copying is needed anyway to provide reentrancity; thus
# the conversion is not expensive
proc TimeInfoToTime(timeInfo: TTimeInfo): TTime =
proc timeInfoToTime(timeInfo: TTimeInfo): TTime =
var cTimeInfo = timeInfo # for C++ we have to make a copy,
# because the header of mktime is broken in my version of libc
return mktime(timeInfoToTM(cTimeInfo))
@@ -498,7 +498,7 @@ elif defined(JS):
result.weekday = weekDays[t.getUTCDay()]
result.yearday = 0
proc TimeInfoToTime*(timeInfo: TTimeInfo): TTime =
proc timeInfoToTime*(timeInfo: TTimeInfo): TTime =
result = internGetTime()
result.setSeconds(timeInfo.second)
result.setMinutes(timeInfo.minute)

View File

@@ -14,8 +14,8 @@
include "system/inclrtl"
type
irune = int # underlying type of TRune
TRune* = distinct irune ## type that can hold any Unicode character
IRune = int # underlying type of TRune
TRune* = distinct IRune ## type that can hold any Unicode character
TRune16* = distinct int16 ## 16 bit Unicode character
proc `<=%`*(a, b: TRune): bool = return int(a) <=% int(b)

View File

@@ -1963,20 +1963,20 @@ when not defined(JS): #and not defined(NimrodVM):
## Template which expands to either stdout or stderr depending on
## `useStdoutAsStdmsg` compile-time switch.
proc Open*(f: var TFile, filename: string,
proc open*(f: var TFile, filename: string,
mode: TFileMode = fmRead, bufSize: int = -1): Bool {.tags: [].}
## Opens a file named `filename` with given `mode`.
##
## Default mode is readonly. Returns true iff the file could be opened.
## This throws no exception if the file could not be opened.
proc Open*(f: var TFile, filehandle: TFileHandle,
proc open*(f: var TFile, filehandle: TFileHandle,
mode: TFileMode = fmRead): Bool {.tags: [].}
## Creates a ``TFile`` from a `filehandle` with given `mode`.
##
## Default mode is readonly. Returns true iff the file could be opened.
proc Open*(filename: string,
proc open*(filename: string,
mode: TFileMode = fmRead, bufSize: int = -1): TFile =
## Opens a file named `filename` with given `mode`.
##
@@ -1993,16 +1993,16 @@ when not defined(JS): #and not defined(NimrodVM):
##
## Default mode is readonly. Returns true iff the file could be reopened.
proc Close*(f: TFile) {.importc: "fclose", header: "<stdio.h>", tags: [].}
proc close*(f: TFile) {.importc: "fclose", header: "<stdio.h>", tags: [].}
## Closes the file.
proc EndOfFile*(f: TFile): Bool {.tags: [].}
proc endOfFile*(f: TFile): Bool {.tags: [].}
## Returns true iff `f` is at the end.
proc readChar*(f: TFile): char {.
importc: "fgetc", header: "<stdio.h>", tags: [FReadIO].}
## Reads a single character from the stream `f`.
proc FlushFile*(f: TFile) {.
proc flushFile*(f: TFile) {.
importc: "fflush", header: "<stdio.h>", tags: [FWriteIO].}
## Flushes `f`'s buffer.
@@ -2051,13 +2051,13 @@ when not defined(JS): #and not defined(NimrodVM):
proc getFileSize*(f: TFile): int64 {.tags: [FReadIO].}
## retrieves the file size (in bytes) of `f`.
proc ReadBytes*(f: TFile, a: var openarray[int8], start, len: int): int {.
proc readBytes*(f: TFile, a: var openarray[int8], start, len: int): int {.
tags: [FReadIO].}
## reads `len` bytes into the buffer `a` starting at ``a[start]``. Returns
## the actual number of bytes that have been read which may be less than
## `len` (if not as many bytes are remaining), but not greater.
proc ReadChars*(f: TFile, a: var openarray[char], start, len: int): int {.
proc readChars*(f: TFile, a: var openarray[char], start, len: int): int {.
tags: [FReadIO].}
## reads `len` bytes into the buffer `a` starting at ``a[start]``. Returns
## the actual number of bytes that have been read which may be less than
@@ -2655,7 +2655,7 @@ proc compiles*(x: expr): bool {.magic: "Compiles", noSideEffect.} =
## .. code-block:: Nimrod
## when not compiles(3 + 4):
## echo "'+' for integers is available"
nil
discard
when defined(initDebugger):
initDebugger()
@@ -2680,4 +2680,4 @@ proc locals*(): TObject {.magic: "Locals", noSideEffect.} =
## on any debug or runtime information. Note that in constrast to what
## the official signature says, the return type is not ``TObject`` but a
## tuple of a structure that depends on the current scope.
nil
discard

View File

@@ -59,15 +59,16 @@ elif defined(windows):
MEM_DECOMMIT = 0x4000
MEM_RELEASE = 0x8000
proc VirtualAlloc(lpAddress: pointer, dwSize: int, flAllocationType,
proc virtualAlloc(lpAddress: pointer, dwSize: int, flAllocationType,
flProtect: int32): pointer {.
header: "<windows.h>", stdcall.}
header: "<windows.h>", stdcall, importc: "VirtualAlloc".}
proc VirtualFree(lpAddress: pointer, dwSize: int,
dwFreeType: int32) {.header: "<windows.h>", stdcall.}
proc virtualFree(lpAddress: pointer, dwSize: int,
dwFreeType: int32) {.header: "<windows.h>", stdcall,
importc: "VirtualFree".}
proc osAllocPages(size: int): pointer {.inline.} =
result = VirtualAlloc(nil, size, MEM_RESERVE or MEM_COMMIT,
result = virtualAlloc(nil, size, MEM_RESERVE or MEM_COMMIT,
PAGE_READWRITE)
if result == nil: raiseOutOfMem()
@@ -78,7 +79,7 @@ elif defined(windows):
# Windows :-(. We have to live with MEM_DECOMMIT instead.
# Well that used to be the case but MEM_DECOMMIT fragments the address
# space heavily, so we now treat Windows as a strange unmap target.
when reallyOsDealloc: VirtualFree(p, 0, MEM_RELEASE)
when reallyOsDealloc: virtualFree(p, 0, MEM_RELEASE)
#VirtualFree(p, size, MEM_DECOMMIT)
else:
@@ -251,14 +252,14 @@ proc llDeallocAll(a: var TMemRegion) =
osDeallocPages(it, PageSize)
it = next
proc IntSetGet(t: TIntSet, key: int): PTrunk =
proc intSetGet(t: TIntSet, key: int): PTrunk =
var it = t.data[key and high(t.data)]
while it != nil:
if it.key == key: return it
it = it.next
result = nil
proc IntSetPut(a: var TMemRegion, t: var TIntSet, key: int): PTrunk =
proc intSetPut(a: var TMemRegion, t: var TIntSet, key: int): PTrunk =
result = IntSetGet(t, key)
if result == nil:
result = cast[PTrunk](llAlloc(a, sizeof(result[])))
@@ -266,7 +267,7 @@ proc IntSetPut(a: var TMemRegion, t: var TIntSet, key: int): PTrunk =
t.data[key and high(t.data)] = result
result.key = key
proc Contains(s: TIntSet, key: int): bool =
proc contains(s: TIntSet, key: int): bool =
var t = IntSetGet(s, key shr TrunkShift)
if t != nil:
var u = key and TrunkMask
@@ -274,12 +275,12 @@ proc Contains(s: TIntSet, key: int): bool =
else:
result = false
proc Incl(a: var TMemRegion, s: var TIntSet, key: int) =
proc incl(a: var TMemRegion, s: var TIntSet, key: int) =
var t = IntSetPut(a, s, key shr TrunkShift)
var u = key and TrunkMask
t.bits[u shr IntShift] = t.bits[u shr IntShift] or (1 shl (u and IntMask))
proc Excl(s: var TIntSet, key: int) =
proc excl(s: var TIntSet, key: int) =
var t = IntSetGet(s, key shr TrunkShift)
if t != nil:
var u = key and TrunkMask
@@ -387,7 +388,7 @@ proc freeOsChunks(a: var TMemRegion, p: pointer, size: int) =
#c_fprintf(c_stdout, "[Alloc] back to OS: %ld\n", size)
proc isAccessible(a: TMemRegion, p: pointer): bool {.inline.} =
result = Contains(a.chunkStarts, pageIndex(p))
result = contains(a.chunkStarts, pageIndex(p))
proc contains[T](list, x: T): bool =
var it = list
@@ -403,7 +404,7 @@ proc writeFreeList(a: TMemRegion) =
it, it.next, it.prev)
it = it.next
proc ListAdd[T](head: var T, c: T) {.inline.} =
proc listAdd[T](head: var T, c: T) {.inline.} =
sysAssert(c notin head, "listAdd 1")
sysAssert c.prev == nil, "listAdd 2"
sysAssert c.next == nil, "listAdd 3"
@@ -413,7 +414,7 @@ proc ListAdd[T](head: var T, c: T) {.inline.} =
head.prev = c
head = c
proc ListRemove[T](head: var T, c: T) {.inline.} =
proc listRemove[T](head: var T, c: T) {.inline.} =
sysAssert(c in head, "listRemove")
if c == head:
head = c.next
@@ -759,7 +760,7 @@ proc getOccupiedMem(a: TMemRegion): int {.inline.} =
# ---------------------- thread memory region -------------------------------
template InstantiateForRegion(allocator: expr) =
template instantiateForRegion(allocator: expr) =
when defined(fulldebug):
proc interiorAllocatedPtr*(p: pointer): pointer =
result = interiorAllocatedPtr(allocator, p)
@@ -801,13 +802,13 @@ template InstantiateForRegion(allocator: expr) =
when hasThreadSupport:
var sharedHeap: TMemRegion
var heapLock: TSysLock
InitSysLock(HeapLock)
initSysLock(HeapLock)
proc allocShared(size: int): pointer =
when hasThreadSupport:
AcquireSys(HeapLock)
acquireSys(HeapLock)
result = alloc(sharedHeap, size)
ReleaseSys(HeapLock)
releaseSys(HeapLock)
else:
result = alloc(size)
@@ -817,17 +818,17 @@ template InstantiateForRegion(allocator: expr) =
proc deallocShared(p: pointer) =
when hasThreadSupport:
AcquireSys(HeapLock)
acquireSys(HeapLock)
dealloc(sharedHeap, p)
ReleaseSys(HeapLock)
releaseSys(HeapLock)
else:
dealloc(p)
proc reallocShared(p: pointer, newsize: int): pointer =
when hasThreadSupport:
AcquireSys(HeapLock)
acquireSys(HeapLock)
result = realloc(sharedHeap, p, newsize)
ReleaseSys(HeapLock)
releaseSys(HeapLock)
else:
result = realloc(p, newsize)

View File

@@ -168,12 +168,12 @@ proc objectInit(dest: Pointer, typ: PNimType) =
of tyArray, tyArrayConstr:
for i in 0..(typ.size div typ.base.size)-1:
objectInit(cast[pointer](d +% i * typ.base.size), typ.base)
else: nil # nothing to do
else: discard # nothing to do
# ---------------------- assign zero -----------------------------------------
when not defined(nimmixin):
proc destroy(x: int) = nil
proc destroy(x: int) = discard
proc nimDestroyRange*[T](r: T) =
# internal proc used for destroying sequences and arrays
for i in countup(0, r.len - 1): destroy(r[i])

View File

@@ -7,62 +7,60 @@
# distribution, for details about the copyright.
#
# Atomic operations for Nimrod.
## Atomic operations for Nimrod.
when (defined(gcc) or defined(llvm_gcc)) and hasThreadSupport:
when (defined(gcc) or defined(llvm_gcc)) and hasThreadSupport:
type
AtomMemModel* = enum
ATOMIC_RELAXED,
## No barriers or synchronization.
ATOMIC_CONSUME,
## Data dependency only for both barrier and synchronization with another thread.
ATOMIC_ACQUIRE,
## Barrier to hoisting of code and synchronizes with release (or stronger)
## semantic stores from another thread.
ATOMIC_RELEASE,
## Barrier to sinking of code and synchronizes with acquire (or stronger)
## semantic loads from another thread.
ATOMIC_ACQ_REL,
## Full barrier in both directions and synchronizes with acquire loads
## and release stores in another thread.
ATOMIC_SEQ_CST
## Full barrier in both directions and synchronizes with acquire loads
## and release stores in all threads.
ATOMIC_RELAXED, ## No barriers or synchronization.
ATOMIC_CONSUME, ## Data dependency only for both barrier and
## synchronization with another thread.
ATOMIC_ACQUIRE, ## Barrier to hoisting of code and synchronizes with
## release (or stronger)
## semantic stores from another thread.
ATOMIC_RELEASE, ## Barrier to sinking of code and synchronizes with
## acquire (or stronger)
## semantic loads from another thread.
ATOMIC_ACQ_REL, ## Full barrier in both directions and synchronizes
## with acquire loads
## and release stores in another thread.
ATOMIC_SEQ_CST ## Full barrier in both directions and synchronizes
## with acquire loads
## and release stores in all threads.
TAtomType* = TNumber|pointer|ptr|char
## Type Class representing valid types for use with atomic procs
## Type Class representing valid types for use with atomic procs
proc atomic_load_n*[T: TAtomType](p: ptr T, mem: AtomMemModel): T {.
proc atomicLoadN*[T: TAtomType](p: ptr T, mem: AtomMemModel): T {.
importc: "__atomic_load_n", nodecl.}
## This proc implements an atomic load operation. It returns the contents at p.
## ATOMIC_RELAXED, ATOMIC_SEQ_CST, ATOMIC_ACQUIRE, ATOMIC_CONSUME.
proc atomic_load*[T: TAtomType](p: ptr T, ret: ptr T, mem: AtomMemModel) {.
proc atomicLoad*[T: TAtomType](p: ptr T, ret: ptr T, mem: AtomMemModel) {.
importc: "__atomic_load", nodecl.}
## This is the generic version of an atomic load. It returns the contents at p in ret.
proc atomic_store_n*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel) {.
proc atomicStoreN*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel) {.
importc: "__atomic_store_n", nodecl.}
## This proc implements an atomic store operation. It writes val at p.
## ATOMIC_RELAXED, ATOMIC_SEQ_CST, and ATOMIC_RELEASE.
proc atomic_store*[T: TAtomType](p: ptr T, val: ptr T, mem: AtomMemModel) {.
proc atomicStore*[T: TAtomType](p: ptr T, val: ptr T, mem: AtomMemModel) {.
importc: "__atomic_store", nodecl.}
## This is the generic version of an atomic store. It stores the value of val at p
proc atomic_exchange_n*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {.
proc atomicExchangeN*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {.
importc: "__atomic_exchange_n", nodecl.}
## This proc implements an atomic exchange operation. It writes val at p,
## and returns the previous contents at p.
## ATOMIC_RELAXED, ATOMIC_SEQ_CST, ATOMIC_ACQUIRE, ATOMIC_RELEASE, ATOMIC_ACQ_REL
proc atomic_exchange*[T: TAtomType](p: ptr T, val: ptr T, ret: ptr T, mem: AtomMemModel) {.
proc atomicExchange*[T: TAtomType](p: ptr T, val: ptr T, ret: ptr T, mem: AtomMemModel) {.
importc: "__atomic_exchange", nodecl.}
## This is the generic version of an atomic exchange. It stores the contents at val at p.
## The original value at p is copied into ret.
proc atomic_compare_exchange_n*[T: TAtomType](p: ptr T, expected: ptr T, desired: T,
proc atomicCompareExchangeN*[T: TAtomType](p: ptr T, expected: ptr T, desired: T,
weak: bool, success_memmodel: AtomMemModel, failure_memmodel: AtomMemModel): bool {.
importc: "__atomic_compare_exchange_n ", nodecl.}
## This proc implements an atomic compare and exchange operation. This compares the
@@ -78,7 +76,7 @@ when (defined(gcc) or defined(llvm_gcc)) and hasThreadSupport:
## cannot be __ATOMIC_RELEASE nor __ATOMIC_ACQ_REL. It also cannot be a stronger model
## than that specified by success_memmodel.
proc atomic_compare_exchange*[T: TAtomType](p: ptr T, expected: ptr T, desired: ptr T,
proc atomicCompareExchange*[T: TAtomType](p: ptr T, expected: ptr T, desired: ptr T,
weak: bool, success_memmodel: AtomMemModel, failure_memmodel: AtomMemModel): bool {.
importc: "__atomic_compare_exchange_n ", nodecl.}
## This proc implements the generic version of atomic_compare_exchange.
@@ -86,58 +84,58 @@ when (defined(gcc) or defined(llvm_gcc)) and hasThreadSupport:
## value is also a pointer.
## Perform the operation return the new value, all memory models are valid
proc atomic_add_fetch*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {.
proc atomicAddFetch*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {.
importc: "__atomic_add_fetch", nodecl.}
proc atomic_sub_fetch*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {.
proc atomicSubFetch*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {.
importc: "__atomic_sub_fetch", nodecl.}
proc atomic_or_fetch*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {.
proc atomicOrFetch*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {.
importc: "__atomic_or_fetch ", nodecl.}
proc atomic_and_fetch*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {.
proc atomicAndFetch*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {.
importc: "__atomic_and_fetch", nodecl.}
proc atomic_xor_fetch*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {.
proc atomicXorFetch*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {.
importc: "__atomic_xor_fetch", nodecl.}
proc atomic_nand_fetch*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {.
proc atomicNandFetch*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {.
importc: "__atomic_nand_fetch ", nodecl.}
## Perform the operation return the old value, all memory models are valid
proc atomic_fetch_add*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {.
importc: "__atomic_fetch_add ", nodecl.}
proc atomic_fetch_sub*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {.
importc: "__atomic_fetch_sub ", nodecl.}
proc atomic_fetch_or*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {.
importc: "__atomic_fetch_or ", nodecl.}
proc atomic_fetch_and*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {.
importc: "__atomic_fetch_and ", nodecl.}
proc atomic_fetch_xor*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {.
importc: "__atomic_fetch_xor ", nodecl.}
proc atomic_fetch_nand*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {.
proc atomicFetchAdd*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {.
importc: "__atomic_fetch_add", nodecl.}
proc atomicFetchSub*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {.
importc: "__atomic_fetch_sub", nodecl.}
proc atomicFetchOr*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {.
importc: "__atomic_fetch_or", nodecl.}
proc atomicFetchAnd*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {.
importc: "__atomic_fetch_and", nodecl.}
proc atomicFetchXor*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {.
importc: "__atomic_fetch_xor", nodecl.}
proc atomicFetchAand*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {.
importc: "__atomic_fetch_nand", nodecl.}
proc atomic_test_and_set*(p: pointer, mem: AtomMemModel): bool {.
importc: "__atomic_test_and_set ", nodecl.}
proc atomicTestAndSet*(p: pointer, mem: AtomMemModel): bool {.
importc: "__atomic_test_and_set", nodecl.}
## This built-in function performs an atomic test-and-set operation on the byte at p.
## The byte is set to some implementation defined nonzero “set” value and the return
## value is true if and only if the previous contents were “set”.
## All memory models are valid.
proc atomic_clear*(p: pointer, mem: AtomMemModel) {.
proc atomicClear*(p: pointer, mem: AtomMemModel) {.
importc: "__atomic_clear", nodecl.}
## This built-in function performs an atomic clear operation at p.
## After the operation, at p contains 0.
## ATOMIC_RELAXED, ATOMIC_SEQ_CST, ATOMIC_RELEASE
proc atomic_thread_fence*(mem: AtomMemModel) {.
importc: "__atomic_thread_fence ", nodecl.}
proc atomicThreadFence*(mem: AtomMemModel) {.
importc: "__atomic_thread_fence", nodecl.}
## This built-in function acts as a synchronization fence between threads based
## on the specified memory model. All memory orders are valid.
proc atomic_signal_fence*(mem: AtomMemModel) {.
importc: "__atomic_signal_fence ", nodecl.}
proc atomicSignalFence*(mem: AtomMemModel) {.
importc: "__atomic_signal_fence", nodecl.}
## This built-in function acts as a synchronization fence between a thread and
## signal handlers based in the same thread. All memory orders are valid.
proc atomic_always_lock_free*(size: int, p: pointer): bool {.
importc: "__atomic_always_lock_free ", nodecl.}
proc atomicAlwaysLockFree*(size: int, p: pointer): bool {.
importc: "__atomic_always_lock_free", nodecl.}
## This built-in function returns true if objects of size bytes always generate
## lock free atomic instructions for the target architecture. size must resolve
## to a compile-time constant and the result also resolves to a compile-time constant.
@@ -145,8 +143,8 @@ when (defined(gcc) or defined(llvm_gcc)) and hasThreadSupport:
## A value of 0 indicates typical alignment should be used. The compiler may also
## ignore this parameter.
proc atomic_is_lock_free*(size: int, p: pointer): bool {.
importc: "__atomic_is_lock_free ", nodecl.}
proc atomicIsLockFree*(size: int, p: pointer): bool {.
importc: "__atomic_is_lock_free", nodecl.}
## This built-in function returns true if objects of size bytes always generate
## lock free atomic instructions for the target architecture. If it is not known
## to be lock free a call is made to a runtime routine named __atomic_is_lock_free.
@@ -154,19 +152,14 @@ when (defined(gcc) or defined(llvm_gcc)) and hasThreadSupport:
## A value of 0 indicates typical alignment should be used. The compiler may also
## ignore this parameter.
elif defined(vcc) and hasThreadSupport:
proc add_and_fetch*(p: ptr int, val: int): int {.
proc addAndFetch*(p: ptr int, val: int): int {.
importc: "NimXadd", nodecl.}
else:
proc add_and_fetch*(p: ptr int, val: int): int {.inline.} =
proc addAndFetch*(p: ptr int, val: int): int {.inline.} =
inc(p[], val)
result = p[]
# atomic compare and swap (CAS) funcitons to implement lock-free algorithms
#if defined(windows) and not defined(gcc) and hasThreadSupport:
@@ -210,6 +203,3 @@ proc atomicDec*(memLoc: var int, x: int = 1): int =
else:
dec(memLoc, x)
result = memLoc

View File

@@ -9,30 +9,30 @@
# not really an AVL tree anymore, but still balanced ...
template IsBottom(n: PAvlNode): bool = n == bottom
template isBottom(n: PAvlNode): bool = n == bottom
proc lowGauge(n: PAvlNode): int =
var it = n
while not IsBottom(it):
while not isBottom(it):
result = it.key
it = it.link[0]
proc highGauge(n: PAvlNode): int =
result = -1
var it = n
while not IsBottom(it):
while not isBottom(it):
result = it.upperBound
it = it.link[1]
proc find(root: PAvlNode, key: int): PAvlNode =
var it = root
while not IsBottom(it):
while not isBottom(it):
if it.key == key: return it
it = it.link[ord(it.key <% key)]
proc inRange(root: PAvlNode, key: int): PAvlNode =
var it = root
while not IsBottom(it):
while not isBottom(it):
if it.key <=% key and key <% it.upperBound: return it
it = it.link[ord(it.key <% key)]

View File

@@ -43,15 +43,15 @@ type
proc contains(s: TCellSeq, c: PCell): bool {.inline.} =
for i in 0 .. s.len-1:
if s.d[i] == c: return True
return False
if s.d[i] == c: return true
return false
proc add(s: var TCellSeq, c: PCell) {.inline.} =
if s.len >= s.cap:
s.cap = s.cap * 3 div 2
var d = cast[PCellArray](Alloc(s.cap * sizeof(PCell)))
var d = cast[PCellArray](alloc(s.cap * sizeof(PCell)))
copyMem(d, s.d, s.len * sizeof(PCell))
Dealloc(s.d)
dealloc(s.d)
s.d = d
# XXX: realloc?
s.d[s.len] = c
@@ -60,10 +60,10 @@ proc add(s: var TCellSeq, c: PCell) {.inline.} =
proc init(s: var TCellSeq, cap: int = 1024) =
s.len = 0
s.cap = cap
s.d = cast[PCellArray](Alloc0(cap * sizeof(PCell)))
s.d = cast[PCellArray](alloc0(cap * sizeof(PCell)))
proc deinit(s: var TCellSeq) =
Dealloc(s.d)
dealloc(s.d)
s.d = nil
s.len = 0
s.cap = 0
@@ -73,20 +73,20 @@ proc deinit(s: var TCellSeq) =
const
InitCellSetSize = 1024 # must be a power of two!
proc Init(s: var TCellSet) =
s.data = cast[PPageDescArray](Alloc0(InitCellSetSize * sizeof(PPageDesc)))
proc init(s: var TCellSet) =
s.data = cast[PPageDescArray](alloc0(InitCellSetSize * sizeof(PPageDesc)))
s.max = InitCellSetSize-1
s.counter = 0
s.head = nil
proc Deinit(s: var TCellSet) =
proc deinit(s: var TCellSet) =
var it = s.head
while it != nil:
var n = it.next
Dealloc(it)
dealloc(it)
it = n
s.head = nil # play it safe here
Dealloc(s.data)
dealloc(s.data)
s.data = nil
s.counter = 0
@@ -96,14 +96,14 @@ proc nextTry(h, maxHash: int): int {.inline.} =
# generates each int in range(maxHash) exactly once (see any text on
# random-number generation for proof).
proc CellSetGet(t: TCellSet, key: TAddress): PPageDesc =
proc cellSetGet(t: TCellSet, key: TAddress): PPageDesc =
var h = cast[int](key) and t.max
while t.data[h] != nil:
if t.data[h].key == key: return t.data[h]
h = nextTry(h, t.max)
return nil
proc CellSetRawInsert(t: TCellSet, data: PPageDescArray, desc: PPageDesc) =
proc cellSetRawInsert(t: TCellSet, data: PPageDescArray, desc: PPageDesc) =
var h = cast[int](desc.key) and t.max
while data[h] != nil:
sysAssert(data[h] != desc, "CellSetRawInsert 1")
@@ -111,17 +111,17 @@ proc CellSetRawInsert(t: TCellSet, data: PPageDescArray, desc: PPageDesc) =
sysAssert(data[h] == nil, "CellSetRawInsert 2")
data[h] = desc
proc CellSetEnlarge(t: var TCellSet) =
proc cellSetEnlarge(t: var TCellSet) =
var oldMax = t.max
t.max = ((t.max+1)*2)-1
var n = cast[PPageDescArray](Alloc0((t.max + 1) * sizeof(PPageDesc)))
var n = cast[PPageDescArray](alloc0((t.max + 1) * sizeof(PPageDesc)))
for i in 0 .. oldmax:
if t.data[i] != nil:
CellSetRawInsert(t, n, t.data[i])
Dealloc(t.data)
cellSetRawInsert(t, n, t.data[i])
dealloc(t.data)
t.data = n
proc CellSetPut(t: var TCellSet, key: TAddress): PPageDesc =
proc cellSetPut(t: var TCellSet, key: TAddress): PPageDesc =
var h = cast[int](key) and t.max
while true:
var x = t.data[h]
@@ -130,13 +130,13 @@ proc CellSetPut(t: var TCellSet, key: TAddress): PPageDesc =
h = nextTry(h, t.max)
if ((t.max+1)*2 < t.counter*3) or ((t.max+1)-t.counter < 4):
CellSetEnlarge(t)
cellSetEnlarge(t)
inc(t.counter)
h = cast[int](key) and t.max
while t.data[h] != nil: h = nextTry(h, t.max)
sysAssert(t.data[h] == nil, "CellSetPut")
# the new page descriptor goes into result
result = cast[PPageDesc](Alloc0(sizeof(TPageDesc)))
result = cast[PPageDesc](alloc0(sizeof(TPageDesc)))
result.next = t.head
result.key = key
t.head = result
@@ -146,7 +146,7 @@ proc CellSetPut(t: var TCellSet, key: TAddress): PPageDesc =
proc contains(s: TCellSet, cell: PCell): bool =
var u = cast[TAddress](cell)
var t = CellSetGet(s, u shr PageShift)
var t = cellSetGet(s, u shr PageShift)
if t != nil:
u = (u %% PageSize) /% MemAlign
result = (t.bits[u shr IntShift] and (1 shl (u and IntMask))) != 0
@@ -155,13 +155,13 @@ proc contains(s: TCellSet, cell: PCell): bool =
proc incl(s: var TCellSet, cell: PCell) {.noinline.} =
var u = cast[TAddress](cell)
var t = CellSetPut(s, u shr PageShift)
var t = cellSetPut(s, u shr PageShift)
u = (u %% PageSize) /% MemAlign
t.bits[u shr IntShift] = t.bits[u shr IntShift] or (1 shl (u and IntMask))
proc excl(s: var TCellSet, cell: PCell) =
var u = cast[TAddress](cell)
var t = CellSetGet(s, u shr PageShift)
var t = cellSetGet(s, u shr PageShift)
if t != nil:
u = (u %% PageSize) /% MemAlign
t.bits[u shr IntShift] = (t.bits[u shr IntShift] and
@@ -169,7 +169,7 @@ proc excl(s: var TCellSet, cell: PCell) =
proc containsOrIncl(s: var TCellSet, cell: PCell): bool =
var u = cast[TAddress](cell)
var t = CellSetGet(s, u shr PageShift)
var t = cellSetGet(s, u shr PageShift)
if t != nil:
u = (u %% PageSize) /% MemAlign
result = (t.bits[u shr IntShift] and (1 shl (u and IntMask))) != 0
@@ -177,7 +177,7 @@ proc containsOrIncl(s: var TCellSet, cell: PCell): bool =
t.bits[u shr IntShift] = t.bits[u shr IntShift] or
(1 shl (u and IntMask))
else:
Incl(s, cell)
incl(s, cell)
result = false
iterator elements(t: TCellSet): PCell {.inline.} =

View File

@@ -28,7 +28,7 @@ proc nimLoadLibraryError(path: string) =
stdout.rawWrite("\n")
quit(1)
proc ProcAddrError(name: cstring) {.noinline.} =
proc procAddrError(name: cstring) {.noinline.} =
# carefully written to avoid memory allocation:
stdout.rawWrite("could not import: ")
stdout.write(name)
@@ -83,21 +83,22 @@ elif defined(windows) or defined(dos):
type
THINSTANCE {.importc: "HINSTANCE".} = pointer
proc FreeLibrary(lib: THINSTANCE) {.importc, header: "<windows.h>", stdcall.}
proc freeLibrary(lib: THINSTANCE) {.
importc: "FreeLibrary", header: "<windows.h>", stdcall.}
proc winLoadLibrary(path: cstring): THINSTANCE {.
importc: "LoadLibraryA", header: "<windows.h>", stdcall.}
proc GetProcAddress(lib: THINSTANCE, name: cstring): TProcAddr {.
proc getProcAddress(lib: THINSTANCE, name: cstring): TProcAddr {.
importc: "GetProcAddress", header: "<windows.h>", stdcall.}
proc nimUnloadLibrary(lib: TLibHandle) =
FreeLibrary(cast[THINSTANCE](lib))
freeLibrary(cast[THINSTANCE](lib))
proc nimLoadLibrary(path: string): TLibHandle =
result = cast[TLibHandle](winLoadLibrary(path))
proc nimGetProcAddr(lib: TLibHandle, name: cstring): TProcAddr =
result = GetProcAddress(cast[THINSTANCE](lib), name)
if result == nil: ProcAddrError(name)
result = getProcAddress(cast[THINSTANCE](lib), name)
if result == nil: procAddrError(name)
elif defined(mac):
#

View File

@@ -151,7 +151,7 @@ template gcTrace(cell, state: expr): stmt {.immediate.} =
# forward declarations:
proc collectCT(gch: var TGcHeap)
proc IsOnStack*(p: pointer): bool {.noinline.}
proc isOnStack*(p: pointer): bool {.noinline.}
proc forAllChildren(cell: PCell, op: TWalkOp)
proc doOperation(p: pointer, op: TWalkOp)
proc forAllChildrenAux(dest: Pointer, mt: PNimType, op: TWalkOp)
@@ -669,7 +669,7 @@ proc doOperation(p: pointer, op: TWalkOp) =
proc nimGCvisit(d: pointer, op: int) {.compilerRtl.} =
doOperation(d, TWalkOp(op))
proc CollectZCT(gch: var TGcHeap): bool
proc collectZCT(gch: var TGcHeap): bool
when useMarkForDebug or useBackupGc:
proc markStackAndRegistersForSweep(gch: var TGcHeap) {.noinline, cdecl.}

View File

@@ -72,7 +72,7 @@ proc reprEnum(e: int, typ: PNimType): string {.compilerRtl.} =
result = $e & " (invalid data!)"
type
pbyteArray = ptr array[0.. 0xffff, int8]
PByteArray = ptr array[0.. 0xffff, int8]
proc addSetElem(result: var string, elem: int, typ: PNimType) =
case typ.kind

View File

@@ -22,48 +22,48 @@ when defined(Windows):
TSysCond = THandle
proc InitSysLock(L: var TSysLock) {.stdcall, noSideEffect,
proc initSysLock(L: var TSysLock) {.stdcall, noSideEffect,
dynlib: "kernel32", importc: "InitializeCriticalSection".}
## Initializes the lock `L`.
proc TryAcquireSysAux(L: var TSysLock): int32 {.stdcall, noSideEffect,
proc tryAcquireSysAux(L: var TSysLock): int32 {.stdcall, noSideEffect,
dynlib: "kernel32", importc: "TryEnterCriticalSection".}
## Tries to acquire the lock `L`.
proc TryAcquireSys(L: var TSysLock): bool {.inline.} =
proc tryAcquireSys(L: var TSysLock): bool {.inline.} =
result = TryAcquireSysAux(L) != 0'i32
proc AcquireSys(L: var TSysLock) {.stdcall, noSideEffect,
proc acquireSys(L: var TSysLock) {.stdcall, noSideEffect,
dynlib: "kernel32", importc: "EnterCriticalSection".}
## Acquires the lock `L`.
proc ReleaseSys(L: var TSysLock) {.stdcall, noSideEffect,
proc releaseSys(L: var TSysLock) {.stdcall, noSideEffect,
dynlib: "kernel32", importc: "LeaveCriticalSection".}
## Releases the lock `L`.
proc DeinitSys(L: var TSysLock) {.stdcall, noSideEffect,
proc deinitSys(L: var TSysLock) {.stdcall, noSideEffect,
dynlib: "kernel32", importc: "DeleteCriticalSection".}
proc CreateEvent(lpEventAttributes: pointer,
proc createEvent(lpEventAttributes: pointer,
bManualReset, bInitialState: int32,
lpName: cstring): TSysCond {.stdcall, noSideEffect,
dynlib: "kernel32", importc: "CreateEventA".}
proc CloseHandle(hObject: THandle) {.stdcall, noSideEffect,
proc closeHandle(hObject: THandle) {.stdcall, noSideEffect,
dynlib: "kernel32", importc: "CloseHandle".}
proc WaitForSingleObject(hHandle: THandle, dwMilliseconds: int32): int32 {.
proc waitForSingleObject(hHandle: THandle, dwMilliseconds: int32): int32 {.
stdcall, dynlib: "kernel32", importc: "WaitForSingleObject".}
proc SignalSysCond(hEvent: TSysCond) {.stdcall, noSideEffect,
proc signalSysCond(hEvent: TSysCond) {.stdcall, noSideEffect,
dynlib: "kernel32", importc: "SetEvent".}
proc InitSysCond(cond: var TSysCond) {.inline.} =
cond = CreateEvent(nil, 0'i32, 0'i32, nil)
proc DeinitSysCond(cond: var TSysCond) {.inline.} =
CloseHandle(cond)
proc WaitSysCond(cond: var TSysCond, lock: var TSysLock) =
proc initSysCond(cond: var TSysCond) {.inline.} =
cond = createEvent(nil, 0'i32, 0'i32, nil)
proc deinitSysCond(cond: var TSysCond) {.inline.} =
closeHandle(cond)
proc waitSysCond(cond: var TSysCond, lock: var TSysLock) =
releaseSys(lock)
discard WaitForSingleObject(cond, -1'i32)
discard waitForSingleObject(cond, -1'i32)
acquireSys(lock)
else:
@@ -73,29 +73,29 @@ else:
TSysCond {.importc: "pthread_cond_t", pure, final,
header: "<sys/types.h>".} = object
proc InitSysLock(L: var TSysLock, attr: pointer = nil) {.
proc initSysLock(L: var TSysLock, attr: pointer = nil) {.
importc: "pthread_mutex_init", header: "<pthread.h>", noSideEffect.}
proc AcquireSys(L: var TSysLock) {.noSideEffect,
proc acquireSys(L: var TSysLock) {.noSideEffect,
importc: "pthread_mutex_lock", header: "<pthread.h>".}
proc TryAcquireSysAux(L: var TSysLock): cint {.noSideEffect,
proc tryAcquireSysAux(L: var TSysLock): cint {.noSideEffect,
importc: "pthread_mutex_trylock", header: "<pthread.h>".}
proc TryAcquireSys(L: var TSysLock): bool {.inline.} =
result = TryAcquireSysAux(L) == 0'i32
proc tryAcquireSys(L: var TSysLock): bool {.inline.} =
result = tryAcquireSysAux(L) == 0'i32
proc ReleaseSys(L: var TSysLock) {.noSideEffect,
proc releaseSys(L: var TSysLock) {.noSideEffect,
importc: "pthread_mutex_unlock", header: "<pthread.h>".}
proc DeinitSys(L: var TSysLock) {.
proc deinitSys(L: var TSysLock) {.
importc: "pthread_mutex_destroy", header: "<pthread.h>".}
proc InitSysCond(cond: var TSysCond, cond_attr: pointer = nil) {.
proc initSysCond(cond: var TSysCond, cond_attr: pointer = nil) {.
importc: "pthread_cond_init", header: "<pthread.h>".}
proc WaitSysCond(cond: var TSysCond, lock: var TSysLock) {.
proc waitSysCond(cond: var TSysCond, lock: var TSysLock) {.
importc: "pthread_cond_wait", header: "<pthread.h>".}
proc SignalSysCond(cond: var TSysCond) {.
proc signalSysCond(cond: var TSysCond) {.
importc: "pthread_cond_signal", header: "<pthread.h>".}
proc DeinitSysCond(cond: var TSysCond) {.
proc deinitSysCond(cond: var TSysCond) {.
importc: "pthread_cond_destroy", header: "<pthread.h>".}

View File

@@ -96,25 +96,25 @@ const
CREATE_UNICODE_ENVIRONMENT* = 1024'i32
proc CloseHandle*(hObject: THANDLE): WINBOOL {.stdcall, dynlib: "kernel32",
proc closeHandle*(hObject: THANDLE): WINBOOL {.stdcall, dynlib: "kernel32",
importc: "CloseHandle".}
proc ReadFile*(hFile: THandle, Buffer: pointer, nNumberOfBytesToRead: int32,
proc readFile*(hFile: THandle, Buffer: pointer, nNumberOfBytesToRead: int32,
lpNumberOfBytesRead: var int32, lpOverlapped: pointer): WINBOOL{.
stdcall, dynlib: "kernel32", importc: "ReadFile".}
proc WriteFile*(hFile: THandle, Buffer: pointer, nNumberOfBytesToWrite: int32,
proc writeFile*(hFile: THandle, Buffer: pointer, nNumberOfBytesToWrite: int32,
lpNumberOfBytesWritten: var int32,
lpOverlapped: pointer): WINBOOL{.
stdcall, dynlib: "kernel32", importc: "WriteFile".}
proc CreatePipe*(hReadPipe, hWritePipe: var THandle,
proc createPipe*(hReadPipe, hWritePipe: var THandle,
lpPipeAttributes: var TSECURITY_ATTRIBUTES,
nSize: int32): WINBOOL{.
stdcall, dynlib: "kernel32", importc: "CreatePipe".}
when useWinUnicode:
proc CreateProcessW*(lpApplicationName, lpCommandLine: widecstring,
proc createProcessW*(lpApplicationName, lpCommandLine: widecstring,
lpProcessAttributes: ptr TSECURITY_ATTRIBUTES,
lpThreadAttributes: ptr TSECURITY_ATTRIBUTES,
bInheritHandles: WINBOOL, dwCreationFlags: int32,
@@ -124,7 +124,7 @@ when useWinUnicode:
stdcall, dynlib: "kernel32", importc: "CreateProcessW".}
else:
proc CreateProcessA*(lpApplicationName, lpCommandLine: cstring,
proc createProcessA*(lpApplicationName, lpCommandLine: cstring,
lpProcessAttributes: ptr TSECURITY_ATTRIBUTES,
lpThreadAttributes: ptr TSECURITY_ATTRIBUTES,
bInheritHandles: WINBOOL, dwCreationFlags: int32,
@@ -134,74 +134,76 @@ else:
stdcall, dynlib: "kernel32", importc: "CreateProcessA".}
proc SuspendThread*(hThread: THANDLE): int32 {.stdcall, dynlib: "kernel32",
proc suspendThread*(hThread: THANDLE): int32 {.stdcall, dynlib: "kernel32",
importc: "SuspendThread".}
proc ResumeThread*(hThread: THANDLE): int32 {.stdcall, dynlib: "kernel32",
proc resumeThread*(hThread: THANDLE): int32 {.stdcall, dynlib: "kernel32",
importc: "ResumeThread".}
proc WaitForSingleObject*(hHandle: THANDLE, dwMilliseconds: int32): int32 {.
proc waitForSingleObject*(hHandle: THANDLE, dwMilliseconds: int32): int32 {.
stdcall, dynlib: "kernel32", importc: "WaitForSingleObject".}
proc TerminateProcess*(hProcess: THANDLE, uExitCode: int): WINBOOL {.stdcall,
proc terminateProcess*(hProcess: THANDLE, uExitCode: int): WINBOOL {.stdcall,
dynlib: "kernel32", importc: "TerminateProcess".}
proc GetExitCodeProcess*(hProcess: THANDLE, lpExitCode: var int32): WINBOOL {.
proc getExitCodeProcess*(hProcess: THANDLE, lpExitCode: var int32): WINBOOL {.
stdcall, dynlib: "kernel32", importc: "GetExitCodeProcess".}
proc GetStdHandle*(nStdHandle: int32): THANDLE {.stdcall, dynlib: "kernel32",
proc getStdHandle*(nStdHandle: int32): THANDLE {.stdcall, dynlib: "kernel32",
importc: "GetStdHandle".}
proc SetStdHandle*(nStdHandle: int32, hHandle: THANDLE): WINBOOL {.stdcall,
proc setStdHandle*(nStdHandle: int32, hHandle: THANDLE): WINBOOL {.stdcall,
dynlib: "kernel32", importc: "SetStdHandle".}
proc FlushFileBuffers*(hFile: THANDLE): WINBOOL {.stdcall, dynlib: "kernel32",
proc flushFileBuffers*(hFile: THANDLE): WINBOOL {.stdcall, dynlib: "kernel32",
importc: "FlushFileBuffers".}
proc GetLastError*(): int32 {.importc, stdcall, dynlib: "kernel32".}
proc getLastError*(): int32 {.importc: "GetLastError",
stdcall, dynlib: "kernel32".}
when useWinUnicode:
proc FormatMessageW*(dwFlags: int32, lpSource: pointer,
proc formatMessageW*(dwFlags: int32, lpSource: pointer,
dwMessageId, dwLanguageId: int32,
lpBuffer: pointer, nSize: int32,
Arguments: pointer): int32 {.
importc, stdcall, dynlib: "kernel32".}
importc: "FormatMessageW", stdcall, dynlib: "kernel32".}
else:
proc FormatMessageA*(dwFlags: int32, lpSource: pointer,
proc formatMessageA*(dwFlags: int32, lpSource: pointer,
dwMessageId, dwLanguageId: int32,
lpBuffer: pointer, nSize: int32,
Arguments: pointer): int32 {.
importc, stdcall, dynlib: "kernel32".}
importc: "FormatMessageA", stdcall, dynlib: "kernel32".}
proc LocalFree*(p: pointer) {.importc, stdcall, dynlib: "kernel32".}
proc localFree*(p: pointer) {.
importc: "LocalFree", stdcall, dynlib: "kernel32".}
when useWinUnicode:
proc GetCurrentDirectoryW*(nBufferLength: int32,
proc getCurrentDirectoryW*(nBufferLength: int32,
lpBuffer: widecstring): int32 {.
importc, dynlib: "kernel32", stdcall.}
proc SetCurrentDirectoryW*(lpPathName: widecstring): int32 {.
importc, dynlib: "kernel32", stdcall.}
proc CreateDirectoryW*(pathName: widecstring, security: Pointer=nil): int32 {.
importc: "GetCurrentDirectoryW", dynlib: "kernel32", stdcall.}
proc setCurrentDirectoryW*(lpPathName: widecstring): int32 {.
importc: "SetCurrentDirectoryW", dynlib: "kernel32", stdcall.}
proc createDirectoryW*(pathName: widecstring, security: Pointer=nil): int32 {.
importc: "CreateDirectoryW", dynlib: "kernel32", stdcall.}
proc RemoveDirectoryW*(lpPathName: widecstring): int32 {.
importc, dynlib: "kernel32", stdcall.}
proc SetEnvironmentVariableW*(lpName, lpValue: widecstring): int32 {.
stdcall, dynlib: "kernel32", importc.}
proc removeDirectoryW*(lpPathName: widecstring): int32 {.
importc: "RemoveDirectoryW", dynlib: "kernel32", stdcall.}
proc setEnvironmentVariableW*(lpName, lpValue: widecstring): int32 {.
stdcall, dynlib: "kernel32", importc: "SetEnvironmentVariableW".}
proc GetModuleFileNameW*(handle: THandle, buf: wideCString,
size: int32): int32 {.importc,
proc getModuleFileNameW*(handle: THandle, buf: wideCString,
size: int32): int32 {.importc: "GetModuleFileNameW",
dynlib: "kernel32", stdcall.}
else:
proc GetCurrentDirectoryA*(nBufferLength: int32, lpBuffer: cstring): int32 {.
importc, dynlib: "kernel32", stdcall.}
proc SetCurrentDirectoryA*(lpPathName: cstring): int32 {.
importc, dynlib: "kernel32", stdcall.}
proc CreateDirectoryA*(pathName: cstring, security: Pointer=nil): int32 {.
proc getCurrentDirectoryA*(nBufferLength: int32, lpBuffer: cstring): int32 {.
importc: "GetCurrentDirectoryA", dynlib: "kernel32", stdcall.}
proc setCurrentDirectoryA*(lpPathName: cstring): int32 {.
importc: "SetCurrentDirectoryA", dynlib: "kernel32", stdcall.}
proc createDirectoryA*(pathName: cstring, security: Pointer=nil): int32 {.
importc: "CreateDirectoryA", dynlib: "kernel32", stdcall.}
proc RemoveDirectoryA*(lpPathName: cstring): int32 {.
importc, dynlib: "kernel32", stdcall.}
proc SetEnvironmentVariableA*(lpName, lpValue: cstring): int32 {.
stdcall, dynlib: "kernel32", importc.}
proc removeDirectoryA*(lpPathName: cstring): int32 {.
importc: "RemoveDirectoryA", dynlib: "kernel32", stdcall.}
proc setEnvironmentVariableA*(lpName, lpValue: cstring): int32 {.
stdcall, dynlib: "kernel32", importc: "SetEnvironmentVariableA".}
proc GetModuleFileNameA*(handle: THandle, buf: CString, size: int32): int32 {.
importc, dynlib: "kernel32", stdcall.}
proc getModuleFileNameA*(handle: THandle, buf: CString, size: int32): int32 {.
importc: "GetModuleFileNameA", dynlib: "kernel32", stdcall.}
const
FILE_ATTRIBUTE_ARCHIVE* = 32'i32
@@ -228,65 +230,71 @@ type
cAlternateFileName*: array[0..13, TWinChar]
when useWinUnicode:
proc FindFirstFileW*(lpFileName: widecstring,
proc findFirstFileW*(lpFileName: widecstring,
lpFindFileData: var TWIN32_FIND_DATA): THANDLE {.
stdcall, dynlib: "kernel32", importc: "FindFirstFileW".}
proc FindNextFileW*(hFindFile: THANDLE,
proc findNextFileW*(hFindFile: THANDLE,
lpFindFileData: var TWIN32_FIND_DATA): int32 {.
stdcall, dynlib: "kernel32", importc: "FindNextFileW".}
else:
proc FindFirstFileA*(lpFileName: cstring,
proc findFirstFileA*(lpFileName: cstring,
lpFindFileData: var TWIN32_FIND_DATA): THANDLE {.
stdcall, dynlib: "kernel32", importc: "FindFirstFileA".}
proc FindNextFileA*(hFindFile: THANDLE,
proc findNextFileA*(hFindFile: THANDLE,
lpFindFileData: var TWIN32_FIND_DATA): int32 {.
stdcall, dynlib: "kernel32", importc: "FindNextFileA".}
proc FindClose*(hFindFile: THANDLE) {.stdcall, dynlib: "kernel32",
proc findClose*(hFindFile: THANDLE) {.stdcall, dynlib: "kernel32",
importc: "FindClose".}
when useWinUnicode:
proc GetFullPathNameW*(lpFileName: widecstring, nBufferLength: int32,
proc getFullPathNameW*(lpFileName: widecstring, nBufferLength: int32,
lpBuffer: widecstring,
lpFilePart: var widecstring): int32 {.
stdcall, dynlib: "kernel32", importc.}
proc GetFileAttributesW*(lpFileName: widecstring): int32 {.
stdcall, dynlib: "kernel32", importc.}
proc SetFileAttributesW*(lpFileName: widecstring,
stdcall, dynlib: "kernel32",
importc: "GetFullPathNameW".}
proc getFileAttributesW*(lpFileName: widecstring): int32 {.
stdcall, dynlib: "kernel32",
importc: "GetFileAttributesW".}
proc setFileAttributesW*(lpFileName: widecstring,
dwFileAttributes: int32): WINBOOL {.
stdcall, dynlib: "kernel32", importc: "SetFileAttributesW".}
proc CopyFileW*(lpExistingFileName, lpNewFileName: wideCString,
proc copyFileW*(lpExistingFileName, lpNewFileName: wideCString,
bFailIfExists: cint): cint {.
importc, stdcall, dynlib: "kernel32".}
importc: "CopyFileW", stdcall, dynlib: "kernel32".}
proc GetEnvironmentStringsW*(): widecstring {.
stdcall, dynlib: "kernel32", importc.}
proc FreeEnvironmentStringsW*(para1: widecstring): int32 {.
stdcall, dynlib: "kernel32", importc.}
proc getEnvironmentStringsW*(): widecstring {.
stdcall, dynlib: "kernel32", importc: "GetEnvironmentStringsW".}
proc freeEnvironmentStringsW*(para1: widecstring): int32 {.
stdcall, dynlib: "kernel32", importc: "FreeEnvironmentStringsW".}
proc GetCommandLineW*(): wideCString {.importc, stdcall, dynlib: "kernel32".}
proc getCommandLineW*(): wideCString {.importc: "GetCommandLineW",
stdcall, dynlib: "kernel32".}
else:
proc GetFullPathNameA*(lpFileName: cstring, nBufferLength: int32,
proc getFullPathNameA*(lpFileName: cstring, nBufferLength: int32,
lpBuffer: cstring, lpFilePart: var cstring): int32 {.
stdcall, dynlib: "kernel32", importc.}
proc GetFileAttributesA*(lpFileName: cstring): int32 {.
stdcall, dynlib: "kernel32", importc.}
proc SetFileAttributesA*(lpFileName: cstring,
stdcall, dynlib: "kernel32",
importc: "GetFullPathNameA".}
proc getFileAttributesA*(lpFileName: cstring): int32 {.
stdcall, dynlib: "kernel32",
importc: "GetFileAttributesA".}
proc setFileAttributesA*(lpFileName: cstring,
dwFileAttributes: int32): WINBOOL {.
stdcall, dynlib: "kernel32", importc: "SetFileAttributesA".}
proc CopyFileA*(lpExistingFileName, lpNewFileName: CString,
proc copyFileA*(lpExistingFileName, lpNewFileName: CString,
bFailIfExists: cint): cint {.
importc, stdcall, dynlib: "kernel32".}
importc: "CopyFileA", stdcall, dynlib: "kernel32".}
proc GetEnvironmentStringsA*(): cstring {.
stdcall, dynlib: "kernel32", importc.}
proc FreeEnvironmentStringsA*(para1: cstring): int32 {.
stdcall, dynlib: "kernel32", importc.}
proc getEnvironmentStringsA*(): cstring {.
stdcall, dynlib: "kernel32", importc: "GetEnvironmentStringsA".}
proc freeEnvironmentStringsA*(para1: cstring): int32 {.
stdcall, dynlib: "kernel32", importc: "FreeEnvironmentStringsA".}
proc GetCommandLineA*(): CString {.importc, stdcall, dynlib: "kernel32".}
proc getCommandLineA*(): cstring {.
importc: "GetCommandLineA", stdcall, dynlib: "kernel32".}
proc rdFileTime*(f: TFILETIME): int64 =
result = ze64(f.dwLowDateTime) or (ze64(f.dwHighDateTime) shl 32)
@@ -294,25 +302,25 @@ proc rdFileTime*(f: TFILETIME): int64 =
proc rdFileSize*(f: TWin32FindData): int64 =
result = ze64(f.nFileSizeLow) or (ze64(f.nFileSizeHigh) shl 32)
proc GetSystemTimeAsFileTime*(lpSystemTimeAsFileTime: var TFILETIME) {.
proc getSystemTimeAsFileTime*(lpSystemTimeAsFileTime: var TFILETIME) {.
importc: "GetSystemTimeAsFileTime", dynlib: "kernel32", stdcall.}
proc Sleep*(dwMilliseconds: int32){.stdcall, dynlib: "kernel32",
proc sleep*(dwMilliseconds: int32){.stdcall, dynlib: "kernel32",
importc: "Sleep".}
when useWinUnicode:
proc ShellExecuteW*(HWND: THandle, lpOperation, lpFile,
proc shellExecuteW*(HWND: THandle, lpOperation, lpFile,
lpParameters, lpDirectory: widecstring,
nShowCmd: int32): THandle{.
stdcall, dynlib: "shell32.dll", importc: "ShellExecuteW".}
else:
proc ShellExecuteA*(HWND: THandle, lpOperation, lpFile,
proc shellExecuteA*(HWND: THandle, lpOperation, lpFile,
lpParameters, lpDirectory: cstring,
nShowCmd: int32): THandle{.
stdcall, dynlib: "shell32.dll", importc: "ShellExecuteA".}
proc GetFileInformationByHandle*(hFile: THandle,
proc getFileInformationByHandle*(hFile: THandle,
lpFileInformation: ptr TBY_HANDLE_FILE_INFORMATION): WINBOOL{.
stdcall, dynlib: "kernel32", importc: "GetFileInformationByHandle".}
@@ -526,7 +534,7 @@ type
TWOHandleArray* = array[0..MAXIMUM_WAIT_OBJECTS - 1, THANDLE]
PWOHandleArray* = ptr TWOHandleArray
proc WaitForMultipleObjects*(nCount: DWORD, lpHandles: PWOHandleArray,
proc waitForMultipleObjects*(nCount: DWORD, lpHandles: PWOHandleArray,
bWaitAll: WINBOOL, dwMilliseconds: DWORD): DWORD{.
stdcall, dynlib: "kernel32", importc: "WaitForMultipleObjects".}
@@ -558,40 +566,40 @@ const
ERROR_ACCESS_DENIED* = 5
when useWinUnicode:
proc CreateFileW*(lpFileName: widecstring, dwDesiredAccess, dwShareMode: DWORD,
proc createFileW*(lpFileName: widecstring, dwDesiredAccess, dwShareMode: DWORD,
lpSecurityAttributes: pointer,
dwCreationDisposition, dwFlagsAndAttributes: DWORD,
hTemplateFile: THANDLE): THANDLE {.
stdcall, dynlib: "kernel32", importc: "CreateFileW".}
proc DeleteFileW*(pathName: widecstring): int32 {.
proc deleteFileW*(pathName: widecstring): int32 {.
importc: "DeleteFileW", dynlib: "kernel32", stdcall.}
else:
proc CreateFileA*(lpFileName: cstring, dwDesiredAccess, dwShareMode: DWORD,
proc createFileA*(lpFileName: cstring, dwDesiredAccess, dwShareMode: DWORD,
lpSecurityAttributes: pointer,
dwCreationDisposition, dwFlagsAndAttributes: DWORD,
hTemplateFile: THANDLE): THANDLE {.
stdcall, dynlib: "kernel32", importc: "CreateFileA".}
proc DeleteFileA*(pathName: cstring): int32 {.
proc deleteFileA*(pathName: cstring): int32 {.
importc: "DeleteFileA", dynlib: "kernel32", stdcall.}
proc SetEndOfFile*(hFile: THANDLE): WINBOOL {.stdcall, dynlib: "kernel32",
proc setEndOfFile*(hFile: THANDLE): WINBOOL {.stdcall, dynlib: "kernel32",
importc: "SetEndOfFile".}
proc SetFilePointer*(hFile: THANDLE, lDistanceToMove: LONG,
proc setFilePointer*(hFile: THANDLE, lDistanceToMove: LONG,
lpDistanceToMoveHigh: ptr LONG,
dwMoveMethod: DWORD): DWORD {.
stdcall, dynlib: "kernel32", importc: "SetFilePointer".}
proc GetFileSize*(hFile: THANDLE, lpFileSizeHigh: ptr DWORD): DWORD{.stdcall,
proc getFileSize*(hFile: THANDLE, lpFileSizeHigh: ptr DWORD): DWORD{.stdcall,
dynlib: "kernel32", importc: "GetFileSize".}
proc MapViewOfFileEx*(hFileMappingObject: THANDLE, dwDesiredAccess: DWORD,
proc mapViewOfFileEx*(hFileMappingObject: THANDLE, dwDesiredAccess: DWORD,
dwFileOffsetHigh, dwFileOffsetLow: DWORD,
dwNumberOfBytesToMap: DWORD,
lpBaseAddress: pointer): pointer{.
stdcall, dynlib: "kernel32", importc: "MapViewOfFileEx".}
proc CreateFileMappingW*(hFile: THANDLE,
proc createFileMappingW*(hFile: THANDLE,
lpFileMappingAttributes: pointer,
flProtect, dwMaximumSizeHigh: DWORD,
dwMaximumSizeLow: DWORD,
@@ -599,12 +607,12 @@ proc CreateFileMappingW*(hFile: THANDLE,
stdcall, dynlib: "kernel32", importc: "CreateFileMappingW".}
when not useWinUnicode:
proc CreateFileMappingA*(hFile: THANDLE,
proc createFileMappingA*(hFile: THANDLE,
lpFileMappingAttributes: pointer,
flProtect, dwMaximumSizeHigh: DWORD,
dwMaximumSizeLow: DWORD, lpName: cstring): THANDLE {.
stdcall, dynlib: "kernel32", importc: "CreateFileMappingA".}
proc UnmapViewOfFile*(lpBaseAddress: pointer): WINBOOL {.stdcall,
proc unmapViewOfFile*(lpBaseAddress: pointer): WINBOOL {.stdcall,
dynlib: "kernel32", importc: "UnmapViewOfFile".}