renamefest
This commit is contained in:
parent
fc0fda14ae
commit
2f43fdb837
62 changed files with 342 additions and 343 deletions
|
|
@ -799,7 +799,7 @@ type
|
||||||
loc*: TLoc
|
loc*: TLoc
|
||||||
|
|
||||||
TPair*{.final.} = object
|
TPair*{.final.} = object
|
||||||
key*, val*: PObject
|
key*, val*: RootRef
|
||||||
|
|
||||||
TPairSeq* = seq[TPair]
|
TPairSeq* = seq[TPair]
|
||||||
TTable*{.final.} = object # the same as table[PObject] of PObject
|
TTable*{.final.} = object # the same as table[PObject] of PObject
|
||||||
|
|
@ -808,7 +808,7 @@ type
|
||||||
|
|
||||||
TIdPair*{.final.} = object
|
TIdPair*{.final.} = object
|
||||||
key*: PIdObj
|
key*: PIdObj
|
||||||
val*: PObject
|
val*: RootRef
|
||||||
|
|
||||||
TIdPairSeq* = seq[TIdPair]
|
TIdPairSeq* = seq[TIdPair]
|
||||||
TIdTable*{.final.} = object # the same as table[PIdent] of PObject
|
TIdTable*{.final.} = object # the same as table[PIdent] of PObject
|
||||||
|
|
@ -835,7 +835,7 @@ type
|
||||||
counter*: int
|
counter*: int
|
||||||
data*: TNodePairSeq
|
data*: TNodePairSeq
|
||||||
|
|
||||||
TObjectSeq* = seq[PObject]
|
TObjectSeq* = seq[RootRef]
|
||||||
TObjectSet*{.final.} = object
|
TObjectSet*{.final.} = object
|
||||||
counter*: int
|
counter*: int
|
||||||
data*: TObjectSeq
|
data*: TObjectSeq
|
||||||
|
|
|
||||||
|
|
@ -14,7 +14,7 @@
|
||||||
import
|
import
|
||||||
ast, hashes, intsets, strutils, options, msgs, ropes, idents, rodutils
|
ast, hashes, intsets, strutils, options, msgs, ropes, idents, rodutils
|
||||||
|
|
||||||
proc hashNode*(p: PObject): THash
|
proc hashNode*(p: RootRef): THash
|
||||||
proc treeToYaml*(n: PNode, indent: int = 0, maxRecDepth: int = - 1): PRope
|
proc treeToYaml*(n: PNode, indent: int = 0, maxRecDepth: int = - 1): PRope
|
||||||
# Convert a tree into its YAML representation; this is used by the
|
# Convert a tree into its YAML representation; this is used by the
|
||||||
# YAML code generator and it is invaluable for debugging purposes.
|
# YAML code generator and it is invaluable for debugging purposes.
|
||||||
|
|
@ -24,21 +24,21 @@ proc symToYaml*(n: PSym, indent: int = 0, maxRecDepth: int = - 1): PRope
|
||||||
proc lineInfoToStr*(info: TLineInfo): PRope
|
proc lineInfoToStr*(info: TLineInfo): PRope
|
||||||
|
|
||||||
# ----------------------- node sets: ---------------------------------------
|
# ----------------------- node sets: ---------------------------------------
|
||||||
proc objectSetContains*(t: TObjectSet, obj: PObject): bool
|
proc objectSetContains*(t: TObjectSet, obj: RootRef): bool
|
||||||
# returns true whether n is in t
|
# returns true whether n is in t
|
||||||
proc objectSetIncl*(t: var TObjectSet, obj: PObject)
|
proc objectSetIncl*(t: var TObjectSet, obj: RootRef)
|
||||||
# include an element n in the table t
|
# include an element n in the table t
|
||||||
proc objectSetContainsOrIncl*(t: var TObjectSet, obj: PObject): bool
|
proc objectSetContainsOrIncl*(t: var TObjectSet, obj: RootRef): bool
|
||||||
# more are not needed ...
|
# more are not needed ...
|
||||||
|
|
||||||
# ----------------------- (key, val)-Hashtables ----------------------------
|
# ----------------------- (key, val)-Hashtables ----------------------------
|
||||||
proc tablePut*(t: var TTable, key, val: PObject)
|
proc tablePut*(t: var TTable, key, val: RootRef)
|
||||||
proc tableGet*(t: TTable, key: PObject): PObject
|
proc tableGet*(t: TTable, key: RootRef): RootRef
|
||||||
type
|
type
|
||||||
TCmpProc* = proc (key, closure: PObject): bool {.nimcall.} # true if found
|
TCmpProc* = proc (key, closure: RootRef): bool {.nimcall.} # true if found
|
||||||
|
|
||||||
proc tableSearch*(t: TTable, key, closure: PObject,
|
proc tableSearch*(t: TTable, key, closure: RootRef,
|
||||||
comparator: TCmpProc): PObject
|
comparator: TCmpProc): RootRef
|
||||||
# return val as soon as comparator returns true; if this never happens,
|
# return val as soon as comparator returns true; if this never happens,
|
||||||
# nil is returned
|
# nil is returned
|
||||||
|
|
||||||
|
|
@ -79,9 +79,9 @@ proc debug*(n: PType) {.deprecated.}
|
||||||
proc debug*(n: PNode) {.deprecated.}
|
proc debug*(n: PNode) {.deprecated.}
|
||||||
|
|
||||||
# --------------------------- ident tables ----------------------------------
|
# --------------------------- ident tables ----------------------------------
|
||||||
proc idTableGet*(t: TIdTable, key: PIdObj): PObject
|
proc idTableGet*(t: TIdTable, key: PIdObj): RootRef
|
||||||
proc idTableGet*(t: TIdTable, key: int): PObject
|
proc idTableGet*(t: TIdTable, key: int): RootRef
|
||||||
proc idTablePut*(t: var TIdTable, key: PIdObj, val: PObject)
|
proc idTablePut*(t: var TIdTable, key: PIdObj, val: RootRef)
|
||||||
proc idTableHasObjectAsKey*(t: TIdTable, key: PIdObj): bool
|
proc idTableHasObjectAsKey*(t: TIdTable, key: PIdObj): bool
|
||||||
# checks if `t` contains the `key` (compared by the pointer value, not only
|
# checks if `t` contains the `key` (compared by the pointer value, not only
|
||||||
# `key`'s id)
|
# `key`'s id)
|
||||||
|
|
@ -196,7 +196,7 @@ proc getSymFromList(list: PNode, ident: PIdent, start: int = 0): PSym =
|
||||||
else: internalError(list.info, "getSymFromList")
|
else: internalError(list.info, "getSymFromList")
|
||||||
result = nil
|
result = nil
|
||||||
|
|
||||||
proc hashNode(p: PObject): THash =
|
proc hashNode(p: RootRef): THash =
|
||||||
result = hash(cast[pointer](p))
|
result = hash(cast[pointer](p))
|
||||||
|
|
||||||
proc mustRehash(length, counter: int): bool =
|
proc mustRehash(length, counter: int): bool =
|
||||||
|
|
@ -283,7 +283,7 @@ proc symToYamlAux(n: PSym, marker: var TIntSet, indent: int,
|
||||||
result = toRope("null")
|
result = toRope("null")
|
||||||
elif containsOrIncl(marker, n.id):
|
elif containsOrIncl(marker, n.id):
|
||||||
result = ropef("\"$1 @$2\"", [toRope(n.name.s), toRope(
|
result = ropef("\"$1 @$2\"", [toRope(n.name.s), toRope(
|
||||||
strutils.toHex(cast[TAddress](n), sizeof(n) * 2))])
|
strutils.toHex(cast[ByteAddress](n), sizeof(n) * 2))])
|
||||||
else:
|
else:
|
||||||
var ast = treeToYamlAux(n.ast, marker, indent + 2, maxRecDepth - 1)
|
var ast = treeToYamlAux(n.ast, marker, indent + 2, maxRecDepth - 1)
|
||||||
result = ropeConstr(indent, [toRope("kind"),
|
result = ropeConstr(indent, [toRope("kind"),
|
||||||
|
|
@ -304,7 +304,7 @@ proc typeToYamlAux(n: PType, marker: var TIntSet, indent: int,
|
||||||
result = toRope("null")
|
result = toRope("null")
|
||||||
elif containsOrIncl(marker, n.id):
|
elif containsOrIncl(marker, n.id):
|
||||||
result = ropef("\"$1 @$2\"", [toRope($n.kind), toRope(
|
result = ropef("\"$1 @$2\"", [toRope($n.kind), toRope(
|
||||||
strutils.toHex(cast[TAddress](n), sizeof(n) * 2))])
|
strutils.toHex(cast[ByteAddress](n), sizeof(n) * 2))])
|
||||||
else:
|
else:
|
||||||
if sonsLen(n) > 0:
|
if sonsLen(n) > 0:
|
||||||
result = toRope("[")
|
result = toRope("[")
|
||||||
|
|
@ -469,7 +469,7 @@ proc nextTry(h, maxHash: THash): THash =
|
||||||
# generates each int in range(maxHash) exactly once (see any text on
|
# generates each int in range(maxHash) exactly once (see any text on
|
||||||
# random-number generation for proof).
|
# random-number generation for proof).
|
||||||
|
|
||||||
proc objectSetContains(t: TObjectSet, obj: PObject): bool =
|
proc objectSetContains(t: TObjectSet, obj: RootRef): bool =
|
||||||
# returns true whether n is in t
|
# returns true whether n is in t
|
||||||
var h: THash = hashNode(obj) and high(t.data) # start with real hash value
|
var h: THash = hashNode(obj) and high(t.data) # start with real hash value
|
||||||
while t.data[h] != nil:
|
while t.data[h] != nil:
|
||||||
|
|
@ -478,7 +478,7 @@ proc objectSetContains(t: TObjectSet, obj: PObject): bool =
|
||||||
h = nextTry(h, high(t.data))
|
h = nextTry(h, high(t.data))
|
||||||
result = false
|
result = false
|
||||||
|
|
||||||
proc objectSetRawInsert(data: var TObjectSeq, obj: PObject) =
|
proc objectSetRawInsert(data: var TObjectSeq, obj: RootRef) =
|
||||||
var h: THash = hashNode(obj) and high(data)
|
var h: THash = hashNode(obj) and high(data)
|
||||||
while data[h] != nil:
|
while data[h] != nil:
|
||||||
assert(data[h] != obj)
|
assert(data[h] != obj)
|
||||||
|
|
@ -493,12 +493,12 @@ proc objectSetEnlarge(t: var TObjectSet) =
|
||||||
if t.data[i] != nil: objectSetRawInsert(n, t.data[i])
|
if t.data[i] != nil: objectSetRawInsert(n, t.data[i])
|
||||||
swap(t.data, n)
|
swap(t.data, n)
|
||||||
|
|
||||||
proc objectSetIncl(t: var TObjectSet, obj: PObject) =
|
proc objectSetIncl(t: var TObjectSet, obj: RootRef) =
|
||||||
if mustRehash(len(t.data), t.counter): objectSetEnlarge(t)
|
if mustRehash(len(t.data), t.counter): objectSetEnlarge(t)
|
||||||
objectSetRawInsert(t.data, obj)
|
objectSetRawInsert(t.data, obj)
|
||||||
inc(t.counter)
|
inc(t.counter)
|
||||||
|
|
||||||
proc objectSetContainsOrIncl(t: var TObjectSet, obj: PObject): bool =
|
proc objectSetContainsOrIncl(t: var TObjectSet, obj: RootRef): bool =
|
||||||
# returns true if obj is already in the string table:
|
# returns true if obj is already in the string table:
|
||||||
var h: THash = hashNode(obj) and high(t.data)
|
var h: THash = hashNode(obj) and high(t.data)
|
||||||
while true:
|
while true:
|
||||||
|
|
@ -516,7 +516,7 @@ proc objectSetContainsOrIncl(t: var TObjectSet, obj: PObject): bool =
|
||||||
inc(t.counter)
|
inc(t.counter)
|
||||||
result = false
|
result = false
|
||||||
|
|
||||||
proc tableRawGet(t: TTable, key: PObject): int =
|
proc tableRawGet(t: TTable, key: RootRef): int =
|
||||||
var h: THash = hashNode(key) and high(t.data) # start with real hash value
|
var h: THash = hashNode(key) and high(t.data) # start with real hash value
|
||||||
while t.data[h].key != nil:
|
while t.data[h].key != nil:
|
||||||
if t.data[h].key == key:
|
if t.data[h].key == key:
|
||||||
|
|
@ -524,8 +524,8 @@ proc tableRawGet(t: TTable, key: PObject): int =
|
||||||
h = nextTry(h, high(t.data))
|
h = nextTry(h, high(t.data))
|
||||||
result = -1
|
result = -1
|
||||||
|
|
||||||
proc tableSearch(t: TTable, key, closure: PObject,
|
proc tableSearch(t: TTable, key, closure: RootRef,
|
||||||
comparator: TCmpProc): PObject =
|
comparator: TCmpProc): RootRef =
|
||||||
var h: THash = hashNode(key) and high(t.data) # start with real hash value
|
var h: THash = hashNode(key) and high(t.data) # start with real hash value
|
||||||
while t.data[h].key != nil:
|
while t.data[h].key != nil:
|
||||||
if t.data[h].key == key:
|
if t.data[h].key == key:
|
||||||
|
|
@ -535,12 +535,12 @@ proc tableSearch(t: TTable, key, closure: PObject,
|
||||||
h = nextTry(h, high(t.data))
|
h = nextTry(h, high(t.data))
|
||||||
result = nil
|
result = nil
|
||||||
|
|
||||||
proc tableGet(t: TTable, key: PObject): PObject =
|
proc tableGet(t: TTable, key: RootRef): RootRef =
|
||||||
var index = tableRawGet(t, key)
|
var index = tableRawGet(t, key)
|
||||||
if index >= 0: result = t.data[index].val
|
if index >= 0: result = t.data[index].val
|
||||||
else: result = nil
|
else: result = nil
|
||||||
|
|
||||||
proc tableRawInsert(data: var TPairSeq, key, val: PObject) =
|
proc tableRawInsert(data: var TPairSeq, key, val: RootRef) =
|
||||||
var h: THash = hashNode(key) and high(data)
|
var h: THash = hashNode(key) and high(data)
|
||||||
while data[h].key != nil:
|
while data[h].key != nil:
|
||||||
assert(data[h].key != key)
|
assert(data[h].key != key)
|
||||||
|
|
@ -556,7 +556,7 @@ proc tableEnlarge(t: var TTable) =
|
||||||
if t.data[i].key != nil: tableRawInsert(n, t.data[i].key, t.data[i].val)
|
if t.data[i].key != nil: tableRawInsert(n, t.data[i].key, t.data[i].val)
|
||||||
swap(t.data, n)
|
swap(t.data, n)
|
||||||
|
|
||||||
proc tablePut(t: var TTable, key, val: PObject) =
|
proc tablePut(t: var TTable, key, val: RootRef) =
|
||||||
var index = tableRawGet(t, key)
|
var index = tableRawGet(t, key)
|
||||||
if index >= 0:
|
if index >= 0:
|
||||||
t.data[index].val = val
|
t.data[index].val = val
|
||||||
|
|
@ -740,22 +740,22 @@ proc idTableHasObjectAsKey(t: TIdTable, key: PIdObj): bool =
|
||||||
if index >= 0: result = t.data[index].key == key
|
if index >= 0: result = t.data[index].key == key
|
||||||
else: result = false
|
else: result = false
|
||||||
|
|
||||||
proc idTableGet(t: TIdTable, key: PIdObj): PObject =
|
proc idTableGet(t: TIdTable, key: PIdObj): RootRef =
|
||||||
var index = idTableRawGet(t, key.id)
|
var index = idTableRawGet(t, key.id)
|
||||||
if index >= 0: result = t.data[index].val
|
if index >= 0: result = t.data[index].val
|
||||||
else: result = nil
|
else: result = nil
|
||||||
|
|
||||||
proc idTableGet(t: TIdTable, key: int): PObject =
|
proc idTableGet(t: TIdTable, key: int): RootRef =
|
||||||
var index = idTableRawGet(t, key)
|
var index = idTableRawGet(t, key)
|
||||||
if index >= 0: result = t.data[index].val
|
if index >= 0: result = t.data[index].val
|
||||||
else: result = nil
|
else: result = nil
|
||||||
|
|
||||||
iterator pairs*(t: TIdTable): tuple[key: int, value: PObject] =
|
iterator pairs*(t: TIdTable): tuple[key: int, value: RootRef] =
|
||||||
for i in 0..high(t.data):
|
for i in 0..high(t.data):
|
||||||
if t.data[i].key != nil:
|
if t.data[i].key != nil:
|
||||||
yield (t.data[i].key.id, t.data[i].val)
|
yield (t.data[i].key.id, t.data[i].val)
|
||||||
|
|
||||||
proc idTableRawInsert(data: var TIdPairSeq, key: PIdObj, val: PObject) =
|
proc idTableRawInsert(data: var TIdPairSeq, key: PIdObj, val: RootRef) =
|
||||||
var h: THash
|
var h: THash
|
||||||
h = key.id and high(data)
|
h = key.id and high(data)
|
||||||
while data[h].key != nil:
|
while data[h].key != nil:
|
||||||
|
|
@ -765,7 +765,7 @@ proc idTableRawInsert(data: var TIdPairSeq, key: PIdObj, val: PObject) =
|
||||||
data[h].key = key
|
data[h].key = key
|
||||||
data[h].val = val
|
data[h].val = val
|
||||||
|
|
||||||
proc idTablePut(t: var TIdTable, key: PIdObj, val: PObject) =
|
proc idTablePut(t: var TIdTable, key: PIdObj, val: RootRef) =
|
||||||
var
|
var
|
||||||
index: int
|
index: int
|
||||||
n: TIdPairSeq
|
n: TIdPairSeq
|
||||||
|
|
@ -784,7 +784,7 @@ proc idTablePut(t: var TIdTable, key: PIdObj, val: PObject) =
|
||||||
idTableRawInsert(t.data, key, val)
|
idTableRawInsert(t.data, key, val)
|
||||||
inc(t.counter)
|
inc(t.counter)
|
||||||
|
|
||||||
iterator idTablePairs*(t: TIdTable): tuple[key: PIdObj, val: PObject] =
|
iterator idTablePairs*(t: TIdTable): tuple[key: PIdObj, val: RootRef] =
|
||||||
for i in 0 .. high(t.data):
|
for i in 0 .. high(t.data):
|
||||||
if not isNil(t.data[i].key): yield (t.data[i].key, t.data[i].val)
|
if not isNil(t.data[i].key): yield (t.data[i].key, t.data[i].val)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -428,10 +428,10 @@ proc getRecordDesc(m: BModule, typ: PType, name: PRope,
|
||||||
var hasField = false
|
var hasField = false
|
||||||
|
|
||||||
var attribute: PRope =
|
var attribute: PRope =
|
||||||
if tfPacked in typ.flags: toRope(CC[ccompiler].packedPragma)
|
if tfPacked in typ.flags: toRope(CC[cCompiler].packedPragma)
|
||||||
else: nil
|
else: nil
|
||||||
|
|
||||||
result = ropecg(m, CC[ccompiler].structStmtFmt,
|
result = ropecg(m, CC[cCompiler].structStmtFmt,
|
||||||
[structOrUnion(typ), name, attribute])
|
[structOrUnion(typ), name, attribute])
|
||||||
|
|
||||||
if typ.kind == tyObject:
|
if typ.kind == tyObject:
|
||||||
|
|
|
||||||
|
|
@ -149,7 +149,7 @@ proc getUniqueType*(key: PType): PType =
|
||||||
idTablePut(gTypeTable[k], key, key)
|
idTablePut(gTypeTable[k], key, key)
|
||||||
result = key
|
result = key
|
||||||
|
|
||||||
proc tableGetType*(tab: TIdTable, key: PType): PObject =
|
proc tableGetType*(tab: TIdTable, key: PType): RootRef =
|
||||||
# returns nil if we need to declare this type
|
# returns nil if we need to declare this type
|
||||||
result = idTableGet(tab, key)
|
result = idTableGet(tab, key)
|
||||||
if (result == nil) and (tab.counter > 0):
|
if (result == nil) and (tab.counter > 0):
|
||||||
|
|
|
||||||
|
|
@ -284,7 +284,7 @@ proc processSwitch(switch, arg: string, pass: TCmdLinePass, info: TLineInfo) =
|
||||||
if pass in {passCmd2, passPP} and not options.gNoBabelPath:
|
if pass in {passCmd2, passPP} and not options.gNoBabelPath:
|
||||||
expectArg(switch, arg, pass, info)
|
expectArg(switch, arg, pass, info)
|
||||||
let path = processPath(arg, notRelativeToProj=true)
|
let path = processPath(arg, notRelativeToProj=true)
|
||||||
babelpath(path, info)
|
babelPath(path, info)
|
||||||
of "nobabelpath":
|
of "nobabelpath":
|
||||||
expectNoArg(switch, arg, pass, info)
|
expectNoArg(switch, arg, pass, info)
|
||||||
options.gNoBabelPath = true
|
options.gNoBabelPath = true
|
||||||
|
|
|
||||||
|
|
@ -102,7 +102,7 @@ proc crcFromFile(filename: string): TCrc32 =
|
||||||
const
|
const
|
||||||
bufSize = 8000 # don't use 8K for the memory allocator!
|
bufSize = 8000 # don't use 8K for the memory allocator!
|
||||||
var
|
var
|
||||||
bin: TFile
|
bin: File
|
||||||
result = InitCrc32
|
result = InitCrc32
|
||||||
if not open(bin, filename):
|
if not open(bin, filename):
|
||||||
return # not equal if file does not exist
|
return # not equal if file does not exist
|
||||||
|
|
|
||||||
|
|
@ -374,11 +374,11 @@ proc genItem(d: PDoc, n, nameNode: PNode, k: TSymKind) =
|
||||||
cleanPlainSymbol = renderPlainSymbolName(nameNode)
|
cleanPlainSymbol = renderPlainSymbolName(nameNode)
|
||||||
complexSymbol = complexName(k, n, cleanPlainSymbol)
|
complexSymbol = complexName(k, n, cleanPlainSymbol)
|
||||||
plainSymbolRope = toRope(cleanPlainSymbol)
|
plainSymbolRope = toRope(cleanPlainSymbol)
|
||||||
plainSymbolEncRope = toRope(URLEncode(cleanPlainSymbol))
|
plainSymbolEncRope = toRope(URLencode(cleanPlainSymbol))
|
||||||
itemIDRope = toRope(d.id)
|
itemIDRope = toRope(d.id)
|
||||||
symbolOrId = d.newUniquePlainSymbol(complexSymbol)
|
symbolOrId = d.newUniquePlainSymbol(complexSymbol)
|
||||||
symbolOrIdRope = symbolOrId.toRope
|
symbolOrIdRope = symbolOrId.toRope
|
||||||
symbolOrIdEncRope = URLEncode(symbolOrId).toRope
|
symbolOrIdEncRope = URLencode(symbolOrId).toRope
|
||||||
|
|
||||||
var seeSrcRope: PRope = nil
|
var seeSrcRope: PRope = nil
|
||||||
let docItemSeeSrc = getConfigVar("doc.item.seesrc")
|
let docItemSeeSrc = getConfigVar("doc.item.seesrc")
|
||||||
|
|
|
||||||
|
|
@ -26,7 +26,7 @@ proc close(p: PPassContext, n: PNode): PNode =
|
||||||
writeOutput(g.doc, g.module.filename, HtmlExt, useWarning)
|
writeOutput(g.doc, g.module.filename, HtmlExt, useWarning)
|
||||||
try:
|
try:
|
||||||
generateIndex(g.doc)
|
generateIndex(g.doc)
|
||||||
except EIO:
|
except IOError:
|
||||||
discard
|
discard
|
||||||
|
|
||||||
proc processNode(c: PPassContext, n: PNode): PNode =
|
proc processNode(c: PPassContext, n: PNode): PNode =
|
||||||
|
|
|
||||||
|
|
@ -551,7 +551,7 @@ proc footprint(filename: string): TCrc32 =
|
||||||
proc externalFileChanged(filename: string): bool =
|
proc externalFileChanged(filename: string): bool =
|
||||||
var crcFile = toGeneratedFile(filename.withPackageName, "crc")
|
var crcFile = toGeneratedFile(filename.withPackageName, "crc")
|
||||||
var currentCrc = int(footprint(filename))
|
var currentCrc = int(footprint(filename))
|
||||||
var f: TFile
|
var f: File
|
||||||
if open(f, crcFile, fmRead):
|
if open(f, crcFile, fmRead):
|
||||||
var line = newStringOfCap(40)
|
var line = newStringOfCap(40)
|
||||||
if not f.readLine(line): line = "0"
|
if not f.readLine(line): line = "0"
|
||||||
|
|
|
||||||
|
|
@ -15,7 +15,7 @@ import
|
||||||
hashes, strutils
|
hashes, strutils
|
||||||
|
|
||||||
type
|
type
|
||||||
TIdObj* = object of TObject
|
TIdObj* = object of RootObj
|
||||||
id*: int # unique id; use this for comparisons and not the pointers
|
id*: int # unique id; use this for comparisons and not the pointers
|
||||||
|
|
||||||
PIdObj* = ref TIdObj
|
PIdObj* = ref TIdObj
|
||||||
|
|
|
||||||
|
|
@ -53,7 +53,7 @@ proc saveMaxIds*(project: string) =
|
||||||
f.close()
|
f.close()
|
||||||
|
|
||||||
proc loadMaxIds*(project: string) =
|
proc loadMaxIds*(project: string) =
|
||||||
var f: TFile
|
var f: File
|
||||||
if open(f, project.toGid, fmRead):
|
if open(f, project.toGid, fmRead):
|
||||||
var line = newStringOfCap(20)
|
var line = newStringOfCap(20)
|
||||||
if f.readLine(line):
|
if f.readLine(line):
|
||||||
|
|
|
||||||
|
|
@ -128,7 +128,7 @@ type
|
||||||
obj: PType
|
obj: PType
|
||||||
|
|
||||||
PEnv = ref TEnv
|
PEnv = ref TEnv
|
||||||
TEnv {.final.} = object of TObject
|
TEnv {.final.} = object of RootObj
|
||||||
attachedNode, replacementNode: PNode
|
attachedNode, replacementNode: PNode
|
||||||
createdVar: PNode # if != nil it is a used environment; for closure
|
createdVar: PNode # if != nil it is a used environment; for closure
|
||||||
# iterators this can be 'envParam.env'
|
# iterators this can be 'envParam.env'
|
||||||
|
|
|
||||||
|
|
@ -429,9 +429,9 @@ proc getNumber(L: var TLexer): TToken =
|
||||||
elif result.tokType == tkInt16Lit and
|
elif result.tokType == tkInt16Lit and
|
||||||
(result.iNumber < int16.low or result.iNumber > int16.high):
|
(result.iNumber < int16.low or result.iNumber > int16.high):
|
||||||
lexMessage(L, errNumberOutOfRange, result.literal)
|
lexMessage(L, errNumberOutOfRange, result.literal)
|
||||||
except EInvalidValue:
|
except ValueError:
|
||||||
lexMessage(L, errInvalidNumber, result.literal)
|
lexMessage(L, errInvalidNumber, result.literal)
|
||||||
except EOverflow, EOutOfRange:
|
except OverflowError, EOutOfRange:
|
||||||
lexMessage(L, errNumberOutOfRange, result.literal)
|
lexMessage(L, errNumberOutOfRange, result.literal)
|
||||||
L.bufpos = endpos
|
L.bufpos = endpos
|
||||||
|
|
||||||
|
|
@ -519,7 +519,7 @@ proc handleCRLF(L: var TLexer, pos: int): int =
|
||||||
lexMessagePos(L, hintLineTooLong, pos)
|
lexMessagePos(L, hintLineTooLong, pos)
|
||||||
|
|
||||||
if optEmbedOrigSrc in gGlobalOptions:
|
if optEmbedOrigSrc in gGlobalOptions:
|
||||||
let lineStart = cast[TAddress](L.buf) + L.lineStart
|
let lineStart = cast[ByteAddress](L.buf) + L.lineStart
|
||||||
let line = newString(cast[cstring](lineStart), col)
|
let line = newString(cast[cstring](lineStart), col)
|
||||||
addSourceLine(L.fileIdx, line)
|
addSourceLine(L.fileIdx, line)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -12,7 +12,7 @@
|
||||||
import os
|
import os
|
||||||
type
|
type
|
||||||
PListEntry* = ref TListEntry
|
PListEntry* = ref TListEntry
|
||||||
TListEntry* = object of TObject
|
TListEntry* = object of RootObj
|
||||||
prev*, next*: PListEntry
|
prev*, next*: PListEntry
|
||||||
|
|
||||||
TStrEntry* = object of TListEntry
|
TStrEntry* = object of TListEntry
|
||||||
|
|
|
||||||
|
|
@ -21,9 +21,9 @@ type
|
||||||
llsString, # stream encapsulates a string
|
llsString, # stream encapsulates a string
|
||||||
llsFile, # stream encapsulates a file
|
llsFile, # stream encapsulates a file
|
||||||
llsStdIn # stream encapsulates stdin
|
llsStdIn # stream encapsulates stdin
|
||||||
TLLStream* = object of TObject
|
TLLStream* = object of RootObj
|
||||||
kind*: TLLStreamKind # accessible for low-level access (lexbase uses this)
|
kind*: TLLStreamKind # accessible for low-level access (lexbase uses this)
|
||||||
f*: TFile
|
f*: File
|
||||||
s*: string
|
s*: string
|
||||||
rd*, wr*: int # for string streams
|
rd*, wr*: int # for string streams
|
||||||
lineOffset*: int # for fake stdin line numbers
|
lineOffset*: int # for fake stdin line numbers
|
||||||
|
|
@ -31,8 +31,8 @@ type
|
||||||
PLLStream* = ref TLLStream
|
PLLStream* = ref TLLStream
|
||||||
|
|
||||||
proc llStreamOpen*(data: string): PLLStream
|
proc llStreamOpen*(data: string): PLLStream
|
||||||
proc llStreamOpen*(f: var TFile): PLLStream
|
proc llStreamOpen*(f: var File): PLLStream
|
||||||
proc llStreamOpen*(filename: string, mode: TFileMode): PLLStream
|
proc llStreamOpen*(filename: string, mode: FileMode): PLLStream
|
||||||
proc llStreamOpen*(): PLLStream
|
proc llStreamOpen*(): PLLStream
|
||||||
proc llStreamOpenStdIn*(): PLLStream
|
proc llStreamOpenStdIn*(): PLLStream
|
||||||
proc llStreamClose*(s: PLLStream)
|
proc llStreamClose*(s: PLLStream)
|
||||||
|
|
@ -50,12 +50,12 @@ proc llStreamOpen(data: string): PLLStream =
|
||||||
result.s = data
|
result.s = data
|
||||||
result.kind = llsString
|
result.kind = llsString
|
||||||
|
|
||||||
proc llStreamOpen(f: var TFile): PLLStream =
|
proc llStreamOpen(f: var File): PLLStream =
|
||||||
new(result)
|
new(result)
|
||||||
result.f = f
|
result.f = f
|
||||||
result.kind = llsFile
|
result.kind = llsFile
|
||||||
|
|
||||||
proc llStreamOpen(filename: string, mode: TFileMode): PLLStream =
|
proc llStreamOpen(filename: string, mode: FileMode): PLLStream =
|
||||||
new(result)
|
new(result)
|
||||||
result.kind = llsFile
|
result.kind = llsFile
|
||||||
if not open(result.f, filename, mode): result = nil
|
if not open(result.f, filename, mode): result = nil
|
||||||
|
|
|
||||||
|
|
@ -260,7 +260,7 @@ proc createWrapperProc(f: PNode; threadParam, argsParam: PSym;
|
||||||
threadLocalBarrier = addLocalVar(varSection2, nil, argsParam.owner,
|
threadLocalBarrier = addLocalVar(varSection2, nil, argsParam.owner,
|
||||||
barrier.typ, barrier)
|
barrier.typ, barrier)
|
||||||
body.add varSection2
|
body.add varSection2
|
||||||
body.add callCodeGenProc("barrierEnter", threadLocalBarrier.newSymNode)
|
body.add callCodegenProc("barrierEnter", threadLocalBarrier.newSymNode)
|
||||||
var threadLocalProm: PSym
|
var threadLocalProm: PSym
|
||||||
if spawnKind == srByVar:
|
if spawnKind == srByVar:
|
||||||
threadLocalProm = addLocalVar(varSection, nil, argsParam.owner, fv.typ, fv)
|
threadLocalProm = addLocalVar(varSection, nil, argsParam.owner, fv.typ, fv)
|
||||||
|
|
@ -275,7 +275,7 @@ proc createWrapperProc(f: PNode; threadParam, argsParam: PSym;
|
||||||
body.add newAsgnStmt(indirectAccess(threadLocalProm.newSymNode,
|
body.add newAsgnStmt(indirectAccess(threadLocalProm.newSymNode,
|
||||||
"owner", fv.info), threadParam.newSymNode)
|
"owner", fv.info), threadParam.newSymNode)
|
||||||
|
|
||||||
body.add callCodeGenProc("nimArgsPassingDone", threadParam.newSymNode)
|
body.add callCodegenProc("nimArgsPassingDone", threadParam.newSymNode)
|
||||||
if spawnKind == srByVar:
|
if spawnKind == srByVar:
|
||||||
body.add newAsgnStmt(genDeref(threadLocalProm.newSymNode), call)
|
body.add newAsgnStmt(genDeref(threadLocalProm.newSymNode), call)
|
||||||
elif fv != nil:
|
elif fv != nil:
|
||||||
|
|
@ -288,11 +288,11 @@ proc createWrapperProc(f: PNode; threadParam, argsParam: PSym;
|
||||||
if barrier == nil:
|
if barrier == nil:
|
||||||
# by now 'fv' is shared and thus might have beeen overwritten! we need
|
# by now 'fv' is shared and thus might have beeen overwritten! we need
|
||||||
# to use the thread-local view instead:
|
# to use the thread-local view instead:
|
||||||
body.add callCodeGenProc("nimFlowVarSignal", threadLocalProm.newSymNode)
|
body.add callCodegenProc("nimFlowVarSignal", threadLocalProm.newSymNode)
|
||||||
else:
|
else:
|
||||||
body.add call
|
body.add call
|
||||||
if barrier != nil:
|
if barrier != nil:
|
||||||
body.add callCodeGenProc("barrierLeave", threadLocalBarrier.newSymNode)
|
body.add callCodegenProc("barrierLeave", threadLocalBarrier.newSymNode)
|
||||||
|
|
||||||
var params = newNodeI(nkFormalParams, f.info)
|
var params = newNodeI(nkFormalParams, f.info)
|
||||||
params.add emptyNode
|
params.add emptyNode
|
||||||
|
|
@ -542,7 +542,7 @@ proc wrapProcForSpawn*(owner: PSym; spawnExpr: PNode; retType: PType;
|
||||||
# create flowVar:
|
# create flowVar:
|
||||||
result.add newFastAsgnStmt(fvField, callProc(spawnExpr[2]))
|
result.add newFastAsgnStmt(fvField, callProc(spawnExpr[2]))
|
||||||
if barrier == nil:
|
if barrier == nil:
|
||||||
result.add callCodeGenProc("nimFlowVarCreateCondVar", fvField)
|
result.add callCodegenProc("nimFlowVarCreateCondVar", fvField)
|
||||||
|
|
||||||
elif spawnKind == srByVar:
|
elif spawnKind == srByVar:
|
||||||
var field = newSym(skField, getIdent"fv", owner, n.info)
|
var field = newSym(skField, getIdent"fv", owner, n.info)
|
||||||
|
|
@ -555,7 +555,7 @@ proc wrapProcForSpawn*(owner: PSym; spawnExpr: PNode; retType: PType;
|
||||||
let wrapper = createWrapperProc(fn, threadParam, argsParam,
|
let wrapper = createWrapperProc(fn, threadParam, argsParam,
|
||||||
varSection, varInit, call,
|
varSection, varInit, call,
|
||||||
barrierAsExpr, fvAsExpr, spawnKind)
|
barrierAsExpr, fvAsExpr, spawnKind)
|
||||||
result.add callCodeGenProc("nimSpawn", wrapper.newSymNode,
|
result.add callCodegenProc("nimSpawn", wrapper.newSymNode,
|
||||||
genAddrOf(scratchObj.newSymNode))
|
genAddrOf(scratchObj.newSymNode))
|
||||||
|
|
||||||
if spawnKind == srFlowVar: result.add fvField
|
if spawnKind == srFlowVar: result.add fvField
|
||||||
|
|
|
||||||
|
|
@ -177,7 +177,7 @@ proc includeModule*(s: PSym, fileIdx: int32): PNode {.procvar.} =
|
||||||
proc `==^`(a, b: string): bool =
|
proc `==^`(a, b: string): bool =
|
||||||
try:
|
try:
|
||||||
result = sameFile(a, b)
|
result = sameFile(a, b)
|
||||||
except EOS:
|
except OSError:
|
||||||
result = false
|
result = false
|
||||||
|
|
||||||
proc compileSystemModule* =
|
proc compileSystemModule* =
|
||||||
|
|
|
||||||
|
|
@ -468,8 +468,8 @@ type
|
||||||
|
|
||||||
TErrorOutputs* = set[TErrorOutput]
|
TErrorOutputs* = set[TErrorOutput]
|
||||||
|
|
||||||
ERecoverableError* = object of EInvalidValue
|
ERecoverableError* = object of ValueError
|
||||||
ESuggestDone* = object of E_Base
|
ESuggestDone* = object of Exception
|
||||||
|
|
||||||
const
|
const
|
||||||
InvalidFileIDX* = int32(-1)
|
InvalidFileIDX* = int32(-1)
|
||||||
|
|
@ -858,7 +858,7 @@ proc sourceLine*(i: TLineInfo): PRope =
|
||||||
try:
|
try:
|
||||||
for line in lines(i.toFullPath):
|
for line in lines(i.toFullPath):
|
||||||
addSourceLine i.fileIndex, line.string
|
addSourceLine i.fileIndex, line.string
|
||||||
except EIO:
|
except IOError:
|
||||||
discard
|
discard
|
||||||
internalAssert i.fileIndex < fileInfos.len
|
internalAssert i.fileIndex < fileInfos.len
|
||||||
# can happen if the error points to EOF:
|
# can happen if the error points to EOF:
|
||||||
|
|
|
||||||
|
|
@ -37,7 +37,7 @@ const
|
||||||
NewLines* = {CR, LF}
|
NewLines* = {CR, LF}
|
||||||
|
|
||||||
type
|
type
|
||||||
TBaseLexer* = object of TObject
|
TBaseLexer* = object of RootObj
|
||||||
bufpos*: int
|
bufpos*: int
|
||||||
buf*: cstring
|
buf*: cstring
|
||||||
bufLen*: int # length of buffer in characters
|
bufLen*: int # length of buffer in characters
|
||||||
|
|
|
||||||
|
|
@ -40,7 +40,7 @@ proc handleCmdLine() =
|
||||||
if gProjectName != "":
|
if gProjectName != "":
|
||||||
try:
|
try:
|
||||||
gProjectFull = canonicalizePath(gProjectName)
|
gProjectFull = canonicalizePath(gProjectName)
|
||||||
except EOS:
|
except OSError:
|
||||||
gProjectFull = gProjectName
|
gProjectFull = gProjectName
|
||||||
var p = splitFile(gProjectFull)
|
var p = splitFile(gProjectFull)
|
||||||
gProjectPath = p.dir
|
gProjectPath = p.dir
|
||||||
|
|
|
||||||
|
|
@ -295,7 +295,7 @@ proc completeGeneratedFilePath*(f: string, createSubDir: bool = true): string =
|
||||||
createDir(subdir)
|
createDir(subdir)
|
||||||
when noTimeMachine:
|
when noTimeMachine:
|
||||||
excludeDirFromTimeMachine(subdir)
|
excludeDirFromTimeMachine(subdir)
|
||||||
except EOS:
|
except OSError:
|
||||||
writeln(stdout, "cannot create directory: " & subdir)
|
writeln(stdout, "cannot create directory: " & subdir)
|
||||||
quit(1)
|
quit(1)
|
||||||
result = joinPath(subdir, tail)
|
result = joinPath(subdir, tail)
|
||||||
|
|
|
||||||
|
|
@ -84,7 +84,7 @@ proc openParser*(p: var TParser, fileIdx: int32, inputStream: PLLStream,
|
||||||
|
|
||||||
proc openParser*(p: var TParser, filename: string, inputStream: PLLStream,
|
proc openParser*(p: var TParser, filename: string, inputStream: PLLStream,
|
||||||
strongSpaces=false) =
|
strongSpaces=false) =
|
||||||
openParser(p, filename.fileInfoIdx, inputstream, strongSpaces)
|
openParser(p, filename.fileInfoIdx, inputStream, strongSpaces)
|
||||||
|
|
||||||
proc closeParser(p: var TParser) =
|
proc closeParser(p: var TParser) =
|
||||||
## Close a parser, freeing up its resources.
|
## Close a parser, freeing up its resources.
|
||||||
|
|
|
||||||
|
|
@ -16,7 +16,7 @@ import
|
||||||
nimsets, syntaxes, times, rodread, idgen
|
nimsets, syntaxes, times, rodread, idgen
|
||||||
|
|
||||||
type
|
type
|
||||||
TPassContext* = object of TObject # the pass's context
|
TPassContext* = object of RootObj # the pass's context
|
||||||
fromCache*: bool # true if created by "openCached"
|
fromCache*: bool # true if created by "openCached"
|
||||||
|
|
||||||
PPassContext* = ref TPassContext
|
PPassContext* = ref TPassContext
|
||||||
|
|
|
||||||
|
|
@ -38,7 +38,7 @@ proc overwriteFiles*() =
|
||||||
f.write line
|
f.write line
|
||||||
f.write("\L")
|
f.write("\L")
|
||||||
f.close
|
f.close
|
||||||
except EIO:
|
except IOError:
|
||||||
rawMessage(errCannotOpenFile, newFile)
|
rawMessage(errCannotOpenFile, newFile)
|
||||||
|
|
||||||
proc `=~`(s: string, a: openArray[string]): bool =
|
proc `=~`(s: string, a: openArray[string]): bool =
|
||||||
|
|
|
||||||
|
|
@ -41,7 +41,7 @@ proc differ*(line: string, a, b: int, x: string): bool =
|
||||||
let y = line[a..b]
|
let y = line[a..b]
|
||||||
result = cmpIgnoreStyle(y, x) == 0 and y != x
|
result = cmpIgnoreStyle(y, x) == 0 and y != x
|
||||||
|
|
||||||
proc replaceDeprecated*(info: TlineInfo; oldSym, newSym: PSym) =
|
proc replaceDeprecated*(info: TLineInfo; oldSym, newSym: PSym) =
|
||||||
loadFile(info)
|
loadFile(info)
|
||||||
|
|
||||||
let line = gSourceFiles[info.fileIndex].lines[info.line-1]
|
let line = gSourceFiles[info.fileIndex].lines[info.line-1]
|
||||||
|
|
|
||||||
|
|
@ -1306,7 +1306,7 @@ proc renderTree(n: PNode, renderFlags: TRenderFlags = {}): string =
|
||||||
proc renderModule(n: PNode, filename: string,
|
proc renderModule(n: PNode, filename: string,
|
||||||
renderFlags: TRenderFlags = {}) =
|
renderFlags: TRenderFlags = {}) =
|
||||||
var
|
var
|
||||||
f: TFile
|
f: File
|
||||||
g: TSrcGen
|
g: TSrcGen
|
||||||
initSrcGen(g, renderFlags)
|
initSrcGen(g, renderFlags)
|
||||||
for i in countup(0, sonsLen(n) - 1):
|
for i in countup(0, sonsLen(n) - 1):
|
||||||
|
|
|
||||||
|
|
@ -121,7 +121,7 @@ type
|
||||||
r*: string # writers use this
|
r*: string # writers use this
|
||||||
offset*: int # readers use this
|
offset*: int # readers use this
|
||||||
|
|
||||||
TRodReader* = object of TObject
|
TRodReader* = object of RootObj
|
||||||
pos: int # position; used for parsing
|
pos: int # position; used for parsing
|
||||||
s: cstring # mmap'ed file contents
|
s: cstring # mmap'ed file contents
|
||||||
options: TOptions
|
options: TOptions
|
||||||
|
|
@ -503,7 +503,7 @@ proc processCompilerProcs(r: PRodReader, module: PSym) =
|
||||||
idTablePut(r.syms, s, s)
|
idTablePut(r.syms, s, s)
|
||||||
strTableAdd(rodCompilerprocs, s)
|
strTableAdd(rodCompilerprocs, s)
|
||||||
|
|
||||||
proc processIndex(r: PRodReader; idx: var TIndex; outf: TFile = nil) =
|
proc processIndex(r: PRodReader; idx: var TIndex; outf: File = nil) =
|
||||||
var key, val, tmp: int
|
var key, val, tmp: int
|
||||||
inc(r.pos, 2) # skip "(\10"
|
inc(r.pos, 2) # skip "(\10"
|
||||||
inc(r.line)
|
inc(r.line)
|
||||||
|
|
@ -659,7 +659,7 @@ proc newRodReader(modfilename: string, crc: TCrc32,
|
||||||
new(result)
|
new(result)
|
||||||
try:
|
try:
|
||||||
result.memfile = memfiles.open(modfilename)
|
result.memfile = memfiles.open(modfilename)
|
||||||
except EOS:
|
except OSError:
|
||||||
return nil
|
return nil
|
||||||
result.files = @[]
|
result.files = @[]
|
||||||
result.modDeps = @[]
|
result.modDeps = @[]
|
||||||
|
|
@ -916,7 +916,7 @@ initIdTable(gTypeTable)
|
||||||
initStrTable(rodCompilerprocs)
|
initStrTable(rodCompilerprocs)
|
||||||
|
|
||||||
# viewer:
|
# viewer:
|
||||||
proc writeNode(f: TFile; n: PNode) =
|
proc writeNode(f: File; n: PNode) =
|
||||||
f.write("(")
|
f.write("(")
|
||||||
if n != nil:
|
if n != nil:
|
||||||
f.write($n.kind)
|
f.write($n.kind)
|
||||||
|
|
@ -947,7 +947,7 @@ proc writeNode(f: TFile; n: PNode) =
|
||||||
writeNode(f, n.sons[i])
|
writeNode(f, n.sons[i])
|
||||||
f.write(")")
|
f.write(")")
|
||||||
|
|
||||||
proc writeSym(f: TFile; s: PSym) =
|
proc writeSym(f: File; s: PSym) =
|
||||||
if s == nil:
|
if s == nil:
|
||||||
f.write("{}\n")
|
f.write("{}\n")
|
||||||
return
|
return
|
||||||
|
|
@ -985,7 +985,7 @@ proc writeSym(f: TFile; s: PSym) =
|
||||||
f.writeNode(s.ast)
|
f.writeNode(s.ast)
|
||||||
f.write("}\n")
|
f.write("}\n")
|
||||||
|
|
||||||
proc writeType(f: TFile; t: PType) =
|
proc writeType(f: File; t: PType) =
|
||||||
if t == nil:
|
if t == nil:
|
||||||
f.write("[]\n")
|
f.write("[]\n")
|
||||||
return
|
return
|
||||||
|
|
|
||||||
|
|
@ -422,7 +422,7 @@ proc addStmt(w: PRodWriter, n: PNode) =
|
||||||
|
|
||||||
proc writeRod(w: PRodWriter) =
|
proc writeRod(w: PRodWriter) =
|
||||||
processStacks(w, true)
|
processStacks(w, true)
|
||||||
var f: TFile
|
var f: File
|
||||||
if not open(f, completeGeneratedFilePath(changeFileExt(
|
if not open(f, completeGeneratedFilePath(changeFileExt(
|
||||||
w.filename.withPackageName, RodExt)),
|
w.filename.withPackageName, RodExt)),
|
||||||
fmWrite):
|
fmWrite):
|
||||||
|
|
|
||||||
|
|
@ -64,7 +64,7 @@ type
|
||||||
# copy the format strings
|
# copy the format strings
|
||||||
# though it is not necessary)
|
# though it is not necessary)
|
||||||
PRope* = ref TRope
|
PRope* = ref TRope
|
||||||
TRope*{.acyclic.} = object of TObject # the empty rope is represented
|
TRope*{.acyclic.} = object of RootObj # the empty rope is represented
|
||||||
# by nil to safe space
|
# by nil to safe space
|
||||||
left*, right*: PRope
|
left*, right*: PRope
|
||||||
length*: int
|
length*: int
|
||||||
|
|
@ -216,7 +216,7 @@ proc app(a: var PRope, b: PRope) = a = con(a, b)
|
||||||
proc app(a: var PRope, b: string) = a = con(a, b)
|
proc app(a: var PRope, b: string) = a = con(a, b)
|
||||||
proc prepend(a: var PRope, b: PRope) = a = con(b, a)
|
proc prepend(a: var PRope, b: PRope) = a = con(b, a)
|
||||||
|
|
||||||
proc writeRope*(f: TFile, c: PRope) =
|
proc writeRope*(f: File, c: PRope) =
|
||||||
var stack = @[c]
|
var stack = @[c]
|
||||||
while len(stack) > 0:
|
while len(stack) > 0:
|
||||||
var it = pop(stack)
|
var it = pop(stack)
|
||||||
|
|
@ -228,7 +228,7 @@ proc writeRope*(f: TFile, c: PRope) =
|
||||||
write(f, it.data)
|
write(f, it.data)
|
||||||
|
|
||||||
proc writeRope*(head: PRope, filename: string, useWarning = false) =
|
proc writeRope*(head: PRope, filename: string, useWarning = false) =
|
||||||
var f: TFile
|
var f: File
|
||||||
if open(f, filename, fmWrite):
|
if open(f, filename, fmWrite):
|
||||||
if head != nil: writeRope(f, head)
|
if head != nil: writeRope(f, head)
|
||||||
close(f)
|
close(f)
|
||||||
|
|
@ -299,7 +299,7 @@ proc appf(c: var PRope, frmt: TFormatStr, args: varargs[PRope]) =
|
||||||
const
|
const
|
||||||
bufSize = 1024 # 1 KB is reasonable
|
bufSize = 1024 # 1 KB is reasonable
|
||||||
|
|
||||||
proc auxRopeEqualsFile(r: PRope, bin: var TFile, buf: pointer): bool =
|
proc auxRopeEqualsFile(r: PRope, bin: var File, buf: pointer): bool =
|
||||||
if r.data != nil:
|
if r.data != nil:
|
||||||
if r.length > bufSize:
|
if r.length > bufSize:
|
||||||
errorHandler(rTokenTooLong, r.data)
|
errorHandler(rTokenTooLong, r.data)
|
||||||
|
|
@ -312,7 +312,7 @@ proc auxRopeEqualsFile(r: PRope, bin: var TFile, buf: pointer): bool =
|
||||||
if result: result = auxRopeEqualsFile(r.right, bin, buf)
|
if result: result = auxRopeEqualsFile(r.right, bin, buf)
|
||||||
|
|
||||||
proc ropeEqualsFile(r: PRope, f: string): bool =
|
proc ropeEqualsFile(r: PRope, f: string): bool =
|
||||||
var bin: TFile
|
var bin: File
|
||||||
result = open(bin, f)
|
result = open(bin, f)
|
||||||
if not result:
|
if not result:
|
||||||
return # not equal if file does not exist
|
return # not equal if file does not exist
|
||||||
|
|
|
||||||
|
|
@ -683,9 +683,9 @@ proc getConstExpr(m: PSym, n: PNode): PNode =
|
||||||
result = evalIs(n, a)
|
result = evalIs(n, a)
|
||||||
else:
|
else:
|
||||||
result = magicCall(m, n)
|
result = magicCall(m, n)
|
||||||
except EOverflow:
|
except OverflowError:
|
||||||
localError(n.info, errOverOrUnderflow)
|
localError(n.info, errOverOrUnderflow)
|
||||||
except EDivByZero:
|
except DivByZeroError:
|
||||||
localError(n.info, errConstantDivisionByZero)
|
localError(n.info, errConstantDivisionByZero)
|
||||||
of nkAddr:
|
of nkAddr:
|
||||||
var a = getConstExpr(m, n.sons[0])
|
var a = getConstExpr(m, n.sons[0])
|
||||||
|
|
|
||||||
|
|
@ -55,7 +55,7 @@ proc annotateType*(n: PNode, t: PType) =
|
||||||
else:
|
else:
|
||||||
globalError(n.info, "() must have an object or tuple type")
|
globalError(n.info, "() must have an object or tuple type")
|
||||||
of nkBracket:
|
of nkBracket:
|
||||||
if x.kind in {tyArrayConstr, tyArray, tySequence, tyOpenarray}:
|
if x.kind in {tyArrayConstr, tyArray, tySequence, tyOpenArray}:
|
||||||
n.typ = t
|
n.typ = t
|
||||||
for m in n: annotateType(m, x.elemType)
|
for m in n: annotateType(m, x.elemType)
|
||||||
else:
|
else:
|
||||||
|
|
|
||||||
|
|
@ -320,7 +320,7 @@ proc analyse(c: var AnalysisCtx; n: PNode) =
|
||||||
# since we already ensure sfAddrTaken is not in s.flags, we only need to
|
# since we already ensure sfAddrTaken is not in s.flags, we only need to
|
||||||
# prevent direct assignments to the monotonic variable:
|
# prevent direct assignments to the monotonic variable:
|
||||||
let slot = c.getSlot(n[0].sym)
|
let slot = c.getSlot(n[0].sym)
|
||||||
slot.blackListed = true
|
slot.blacklisted = true
|
||||||
invalidateFacts(c.guards, n[0])
|
invalidateFacts(c.guards, n[0])
|
||||||
analyseSons(c, n)
|
analyseSons(c, n)
|
||||||
addAsgnFact(c.guards, n[0], n[1])
|
addAsgnFact(c.guards, n[0], n[1])
|
||||||
|
|
@ -464,6 +464,6 @@ proc liftParallel*(owner: PSym; n: PNode): PNode =
|
||||||
result = newNodeI(nkStmtList, n.info)
|
result = newNodeI(nkStmtList, n.info)
|
||||||
generateAliasChecks(a, result)
|
generateAliasChecks(a, result)
|
||||||
result.add varSection
|
result.add varSection
|
||||||
result.add callCodeGenProc("openBarrier", barrier)
|
result.add callCodegenProc("openBarrier", barrier)
|
||||||
result.add transformSpawn(owner, body, barrier)
|
result.add transformSpawn(owner, body, barrier)
|
||||||
result.add callCodeGenProc("closeBarrier", barrier)
|
result.add callCodegenProc("closeBarrier", barrier)
|
||||||
|
|
|
||||||
|
|
@ -44,7 +44,7 @@ proc parseTopLevelStmt*(p: var TParsers): PNode
|
||||||
proc parseFile(fileIdx: int32): PNode =
|
proc parseFile(fileIdx: int32): PNode =
|
||||||
var
|
var
|
||||||
p: TParsers
|
p: TParsers
|
||||||
f: TFile
|
f: File
|
||||||
let filename = fileIdx.toFullPath
|
let filename = fileIdx.toFullPath
|
||||||
if not open(f, filename):
|
if not open(f, filename):
|
||||||
rawMessage(errCannotOpenFile, filename)
|
rawMessage(errCannotOpenFile, filename)
|
||||||
|
|
|
||||||
|
|
@ -24,13 +24,13 @@ proc getProcHeader*(sym: PSym): string
|
||||||
proc base*(t: PType): PType
|
proc base*(t: PType): PType
|
||||||
# ------------------- type iterator: ----------------------------------------
|
# ------------------- type iterator: ----------------------------------------
|
||||||
type
|
type
|
||||||
TTypeIter* = proc (t: PType, closure: PObject): bool {.nimcall.} # true if iteration should stop
|
TTypeIter* = proc (t: PType, closure: RootRef): bool {.nimcall.} # true if iteration should stop
|
||||||
TTypeMutator* = proc (t: PType, closure: PObject): PType {.nimcall.} # copy t and mutate it
|
TTypeMutator* = proc (t: PType, closure: RootRef): PType {.nimcall.} # copy t and mutate it
|
||||||
TTypePredicate* = proc (t: PType): bool {.nimcall.}
|
TTypePredicate* = proc (t: PType): bool {.nimcall.}
|
||||||
|
|
||||||
proc iterOverType*(t: PType, iter: TTypeIter, closure: PObject): bool
|
proc iterOverType*(t: PType, iter: TTypeIter, closure: RootRef): bool
|
||||||
# Returns result of `iter`.
|
# Returns result of `iter`.
|
||||||
proc mutateType*(t: PType, iter: TTypeMutator, closure: PObject): PType
|
proc mutateType*(t: PType, iter: TTypeMutator, closure: RootRef): PType
|
||||||
# Returns result of `iter`.
|
# Returns result of `iter`.
|
||||||
|
|
||||||
type
|
type
|
||||||
|
|
@ -161,9 +161,9 @@ proc enumHasHoles(t: PType): bool =
|
||||||
result = b.kind == tyEnum and tfEnumHasHoles in b.flags
|
result = b.kind == tyEnum and tfEnumHasHoles in b.flags
|
||||||
|
|
||||||
proc iterOverTypeAux(marker: var TIntSet, t: PType, iter: TTypeIter,
|
proc iterOverTypeAux(marker: var TIntSet, t: PType, iter: TTypeIter,
|
||||||
closure: PObject): bool
|
closure: RootRef): bool
|
||||||
proc iterOverNode(marker: var TIntSet, n: PNode, iter: TTypeIter,
|
proc iterOverNode(marker: var TIntSet, n: PNode, iter: TTypeIter,
|
||||||
closure: PObject): bool =
|
closure: RootRef): bool =
|
||||||
if n != nil:
|
if n != nil:
|
||||||
case n.kind
|
case n.kind
|
||||||
of nkNone..nkNilLit:
|
of nkNone..nkNilLit:
|
||||||
|
|
@ -175,7 +175,7 @@ proc iterOverNode(marker: var TIntSet, n: PNode, iter: TTypeIter,
|
||||||
if result: return
|
if result: return
|
||||||
|
|
||||||
proc iterOverTypeAux(marker: var TIntSet, t: PType, iter: TTypeIter,
|
proc iterOverTypeAux(marker: var TIntSet, t: PType, iter: TTypeIter,
|
||||||
closure: PObject): bool =
|
closure: RootRef): bool =
|
||||||
result = false
|
result = false
|
||||||
if t == nil: return
|
if t == nil: return
|
||||||
result = iter(t, closure)
|
result = iter(t, closure)
|
||||||
|
|
@ -190,7 +190,7 @@ proc iterOverTypeAux(marker: var TIntSet, t: PType, iter: TTypeIter,
|
||||||
if result: return
|
if result: return
|
||||||
if t.n != nil: result = iterOverNode(marker, t.n, iter, closure)
|
if t.n != nil: result = iterOverNode(marker, t.n, iter, closure)
|
||||||
|
|
||||||
proc iterOverType(t: PType, iter: TTypeIter, closure: PObject): bool =
|
proc iterOverType(t: PType, iter: TTypeIter, closure: RootRef): bool =
|
||||||
var marker = initIntSet()
|
var marker = initIntSet()
|
||||||
result = iterOverTypeAux(marker, t, iter, closure)
|
result = iterOverTypeAux(marker, t, iter, closure)
|
||||||
|
|
||||||
|
|
@ -354,9 +354,9 @@ proc canFormAcycle(typ: PType): bool =
|
||||||
result = canFormAcycleAux(marker, typ, typ.id)
|
result = canFormAcycleAux(marker, typ, typ.id)
|
||||||
|
|
||||||
proc mutateTypeAux(marker: var TIntSet, t: PType, iter: TTypeMutator,
|
proc mutateTypeAux(marker: var TIntSet, t: PType, iter: TTypeMutator,
|
||||||
closure: PObject): PType
|
closure: RootRef): PType
|
||||||
proc mutateNode(marker: var TIntSet, n: PNode, iter: TTypeMutator,
|
proc mutateNode(marker: var TIntSet, n: PNode, iter: TTypeMutator,
|
||||||
closure: PObject): PNode =
|
closure: RootRef): PNode =
|
||||||
result = nil
|
result = nil
|
||||||
if n != nil:
|
if n != nil:
|
||||||
result = copyNode(n)
|
result = copyNode(n)
|
||||||
|
|
@ -370,7 +370,7 @@ proc mutateNode(marker: var TIntSet, n: PNode, iter: TTypeMutator,
|
||||||
addSon(result, mutateNode(marker, n.sons[i], iter, closure))
|
addSon(result, mutateNode(marker, n.sons[i], iter, closure))
|
||||||
|
|
||||||
proc mutateTypeAux(marker: var TIntSet, t: PType, iter: TTypeMutator,
|
proc mutateTypeAux(marker: var TIntSet, t: PType, iter: TTypeMutator,
|
||||||
closure: PObject): PType =
|
closure: RootRef): PType =
|
||||||
result = nil
|
result = nil
|
||||||
if t == nil: return
|
if t == nil: return
|
||||||
result = iter(t, closure)
|
result = iter(t, closure)
|
||||||
|
|
@ -380,7 +380,7 @@ proc mutateTypeAux(marker: var TIntSet, t: PType, iter: TTypeMutator,
|
||||||
if t.n != nil: result.n = mutateNode(marker, t.n, iter, closure)
|
if t.n != nil: result.n = mutateNode(marker, t.n, iter, closure)
|
||||||
assert(result != nil)
|
assert(result != nil)
|
||||||
|
|
||||||
proc mutateType(t: PType, iter: TTypeMutator, closure: PObject): PType =
|
proc mutateType(t: PType, iter: TTypeMutator, closure: RootRef): PType =
|
||||||
var marker = initIntSet()
|
var marker = initIntSet()
|
||||||
result = mutateTypeAux(marker, t, iter, closure)
|
result = mutateTypeAux(marker, t, iter, closure)
|
||||||
|
|
||||||
|
|
@ -1283,7 +1283,7 @@ proc getSize(typ: PType): BiggestInt =
|
||||||
result = computeSize(typ)
|
result = computeSize(typ)
|
||||||
if result < 0: internalError("getSize: " & $typ.kind)
|
if result < 0: internalError("getSize: " & $typ.kind)
|
||||||
|
|
||||||
proc containsGenericTypeIter(t: PType, closure: PObject): bool =
|
proc containsGenericTypeIter(t: PType, closure: RootRef): bool =
|
||||||
if t.kind == tyStatic:
|
if t.kind == tyStatic:
|
||||||
return t.n == nil
|
return t.n == nil
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -33,6 +33,6 @@ proc opSlurp*(file: string, info: TLineInfo, module: PSym): string =
|
||||||
# the module dependencies are accurate:
|
# the module dependencies are accurate:
|
||||||
appendToModule(module, newNode(nkIncludeStmt, info, @[
|
appendToModule(module, newNode(nkIncludeStmt, info, @[
|
||||||
newStrNode(nkStrLit, filename)]))
|
newStrNode(nkStrLit, filename)]))
|
||||||
except EIO:
|
except IOError:
|
||||||
localError(info, errCannotOpenFile, file)
|
localError(info, errCannotOpenFile, file)
|
||||||
result = ""
|
result = ""
|
||||||
|
|
|
||||||
|
|
@ -97,7 +97,7 @@ type
|
||||||
TNimSymKinds* = set[TNimrodSymKind]
|
TNimSymKinds* = set[TNimrodSymKind]
|
||||||
|
|
||||||
type
|
type
|
||||||
TNimrodIdent* = object of TObject
|
TNimrodIdent* = object of RootObj
|
||||||
## represents a Nimrod identifier in the AST
|
## represents a Nimrod identifier in the AST
|
||||||
|
|
||||||
TNimrodSymbol {.final.} = object # hidden
|
TNimrodSymbol {.final.} = object # hidden
|
||||||
|
|
@ -596,7 +596,7 @@ proc `pragma=`*(someProc: PNimrodNode; val: PNimrodNode){.compileTime.}=
|
||||||
someProc[4] = val
|
someProc[4] = val
|
||||||
|
|
||||||
|
|
||||||
template badnodekind(k; f): stmt{.immediate.} =
|
template badNodeKind(k; f): stmt{.immediate.} =
|
||||||
assert false, "Invalid node kind $# for macros.`$2`".format(k, f)
|
assert false, "Invalid node kind $# for macros.`$2`".format(k, f)
|
||||||
|
|
||||||
proc body*(someProc: PNimrodNode): PNimrodNode {.compileTime.} =
|
proc body*(someProc: PNimrodNode): PNimrodNode {.compileTime.} =
|
||||||
|
|
@ -608,7 +608,7 @@ proc body*(someProc: PNimrodNode): PNimrodNode {.compileTime.} =
|
||||||
of nnkForStmt:
|
of nnkForStmt:
|
||||||
return someProc.last
|
return someProc.last
|
||||||
else:
|
else:
|
||||||
badNodeKind someproc.kind, "body"
|
badNodeKind someProc.kind, "body"
|
||||||
|
|
||||||
proc `body=`*(someProc: PNimrodNode, val: PNimrodNode) {.compileTime.} =
|
proc `body=`*(someProc: PNimrodNode, val: PNimrodNode) {.compileTime.} =
|
||||||
case someProc.kind
|
case someProc.kind
|
||||||
|
|
|
||||||
|
|
@ -23,7 +23,7 @@ type
|
||||||
gtTagStart, gtTagEnd, gtKey, gtValue, gtRawData, gtAssembler,
|
gtTagStart, gtTagEnd, gtKey, gtValue, gtRawData, gtAssembler,
|
||||||
gtPreprocessor, gtDirective, gtCommand, gtRule, gtHyperlink, gtLabel,
|
gtPreprocessor, gtDirective, gtCommand, gtRule, gtHyperlink, gtLabel,
|
||||||
gtReference, gtOther
|
gtReference, gtOther
|
||||||
TGeneralTokenizer* = object of TObject
|
TGeneralTokenizer* = object of RootObj
|
||||||
kind*: TTokenClass
|
kind*: TTokenClass
|
||||||
start*, length*: int
|
start*, length*: int
|
||||||
buf: cstring
|
buf: cstring
|
||||||
|
|
|
||||||
|
|
@ -118,7 +118,7 @@ type
|
||||||
line*, col*: int # line and column of the token
|
line*, col*: int # line and column of the token
|
||||||
|
|
||||||
TTokenSeq = seq[TToken]
|
TTokenSeq = seq[TToken]
|
||||||
TLexer = object of TObject
|
TLexer = object of RootObj
|
||||||
buf*: cstring
|
buf*: cstring
|
||||||
bufpos*: int
|
bufpos*: int
|
||||||
line*, col*, baseIndent*: int
|
line*, col*, baseIndent*: int
|
||||||
|
|
@ -273,7 +273,7 @@ type
|
||||||
findFile: TFindFileHandler # How to find files.
|
findFile: TFindFileHandler # How to find files.
|
||||||
|
|
||||||
PSharedState = ref TSharedState
|
PSharedState = ref TSharedState
|
||||||
TRstParser = object of TObject
|
TRstParser = object of RootObj
|
||||||
idx*: int
|
idx*: int
|
||||||
tok*: TTokenSeq
|
tok*: TTokenSeq
|
||||||
s*: PSharedState
|
s*: PSharedState
|
||||||
|
|
@ -282,7 +282,7 @@ type
|
||||||
line*, col*: int
|
line*, col*: int
|
||||||
hasToc*: bool
|
hasToc*: bool
|
||||||
|
|
||||||
EParseError* = object of EInvalidValue
|
EParseError* = object of ValueError
|
||||||
|
|
||||||
proc whichMsgClass*(k: TMsgKind): TMsgClass =
|
proc whichMsgClass*(k: TMsgKind): TMsgClass =
|
||||||
## returns which message class `k` belongs to.
|
## returns which message class `k` belongs to.
|
||||||
|
|
|
||||||
|
|
@ -42,7 +42,7 @@ type
|
||||||
TMetaEnum* = enum
|
TMetaEnum* = enum
|
||||||
metaNone, metaTitle, metaSubtitle, metaAuthor, metaVersion
|
metaNone, metaTitle, metaSubtitle, metaAuthor, metaVersion
|
||||||
|
|
||||||
TRstGenerator* = object of TObject
|
TRstGenerator* = object of RootObj
|
||||||
target*: TOutputTarget
|
target*: TOutputTarget
|
||||||
config*: PStringTable
|
config*: PStringTable
|
||||||
splitAfter*: int # split too long entries in the TOC
|
splitAfter*: int # split too long entries in the TOC
|
||||||
|
|
@ -1011,7 +1011,7 @@ proc formatNamedVars*(frmt: string, varnames: openArray[string],
|
||||||
inc(i)
|
inc(i)
|
||||||
if i > L-1 or frmt[i] notin {'0'..'9'}: break
|
if i > L-1 or frmt[i] notin {'0'..'9'}: break
|
||||||
if j > high(varvalues) + 1:
|
if j > high(varvalues) + 1:
|
||||||
raise newException(EInvalidValue, "invalid index: " & $j)
|
raise newException(ValueError, "invalid index: " & $j)
|
||||||
num = j
|
num = j
|
||||||
add(result, varvalues[j - 1])
|
add(result, varvalues[j - 1])
|
||||||
of 'A'..'Z', 'a'..'z', '\x80'..'\xFF':
|
of 'A'..'Z', 'a'..'z', '\x80'..'\xFF':
|
||||||
|
|
@ -1024,13 +1024,13 @@ proc formatNamedVars*(frmt: string, varnames: openArray[string],
|
||||||
if idx >= 0:
|
if idx >= 0:
|
||||||
add(result, varvalues[idx])
|
add(result, varvalues[idx])
|
||||||
else:
|
else:
|
||||||
raise newException(EInvalidValue, "unknown substitution var: " & id)
|
raise newException(ValueError, "unknown substitution var: " & id)
|
||||||
of '{':
|
of '{':
|
||||||
var id = ""
|
var id = ""
|
||||||
inc(i)
|
inc(i)
|
||||||
while frmt[i] != '}':
|
while frmt[i] != '}':
|
||||||
if frmt[i] == '\0':
|
if frmt[i] == '\0':
|
||||||
raise newException(EInvalidValue, "'}' expected")
|
raise newException(ValueError, "'}' expected")
|
||||||
add(id, frmt[i])
|
add(id, frmt[i])
|
||||||
inc(i)
|
inc(i)
|
||||||
inc(i) # skip }
|
inc(i) # skip }
|
||||||
|
|
@ -1038,9 +1038,9 @@ proc formatNamedVars*(frmt: string, varnames: openArray[string],
|
||||||
var idx = getVarIdx(varnames, id)
|
var idx = getVarIdx(varnames, id)
|
||||||
if idx >= 0: add(result, varvalues[idx])
|
if idx >= 0: add(result, varvalues[idx])
|
||||||
else:
|
else:
|
||||||
raise newException(EInvalidValue, "unknown substitution var: " & id)
|
raise newException(ValueError, "unknown substitution var: " & id)
|
||||||
else:
|
else:
|
||||||
raise newException(EInvalidValue, "unknown substitution: $" & $frmt[i])
|
raise newException(ValueError, "unknown substitution: $" & $frmt[i])
|
||||||
var start = i
|
var start = i
|
||||||
while i < L:
|
while i < L:
|
||||||
if frmt[i] != '$': inc(i)
|
if frmt[i] != '$': inc(i)
|
||||||
|
|
|
||||||
|
|
@ -69,7 +69,7 @@ proc smartBinarySearch*[T](a: openArray[T], key: T): int =
|
||||||
const
|
const
|
||||||
onlySafeCode = true
|
onlySafeCode = true
|
||||||
|
|
||||||
proc lowerBound*[T](a: openarray[T], key: T, cmp: proc(x,y: T): int {.closure.}): int =
|
proc lowerBound*[T](a: openArray[T], key: T, cmp: proc(x,y: T): int {.closure.}): int =
|
||||||
## same as binarySearch except that if key is not in `a` then this
|
## same as binarySearch except that if key is not in `a` then this
|
||||||
## returns the location where `key` would be if it were. In other
|
## returns the location where `key` would be if it were. In other
|
||||||
## words if you have a sorted sequence and you call insert(thing, elm, lowerBound(thing, elm))
|
## words if you have a sorted sequence and you call insert(thing, elm, lowerBound(thing, elm))
|
||||||
|
|
@ -98,7 +98,7 @@ proc lowerBound*[T](a: openarray[T], key: T, cmp: proc(x,y: T): int {.closure.})
|
||||||
else:
|
else:
|
||||||
count = step
|
count = step
|
||||||
|
|
||||||
proc lowerBound*[T](a: openarray[T], key: T): int = lowerBound(a, key, cmp[T])
|
proc lowerBound*[T](a: openArray[T], key: T): int = lowerBound(a, key, cmp[T])
|
||||||
proc merge[T](a, b: var openArray[T], lo, m, hi: int,
|
proc merge[T](a, b: var openArray[T], lo, m, hi: int,
|
||||||
cmp: proc (x, y: T): int {.closure.}, order: TSortOrder) =
|
cmp: proc (x, y: T): int {.closure.}, order: TSortOrder) =
|
||||||
template `<-` (a, b: expr) =
|
template `<-` (a, b: expr) =
|
||||||
|
|
@ -184,7 +184,7 @@ proc sort*[T](a: var openArray[T],
|
||||||
dec(m, s*2)
|
dec(m, s*2)
|
||||||
s = s*2
|
s = s*2
|
||||||
|
|
||||||
proc product*[T](x: openarray[seq[T]]): seq[seq[T]] =
|
proc product*[T](x: openArray[seq[T]]): seq[seq[T]] =
|
||||||
## produces the Cartesian product of the array. Warning: complexity
|
## produces the Cartesian product of the array. Warning: complexity
|
||||||
## may explode.
|
## may explode.
|
||||||
result = @[]
|
result = @[]
|
||||||
|
|
|
||||||
|
|
@ -93,7 +93,7 @@ proc XMLencode*(s: string): string =
|
||||||
for i in 0..len(s)-1: addXmlChar(result, s[i])
|
for i in 0..len(s)-1: addXmlChar(result, s[i])
|
||||||
|
|
||||||
type
|
type
|
||||||
ECgi* = object of EIO ## the exception that is raised, if a CGI error occurs
|
ECgi* = object of IOError ## the exception that is raised, if a CGI error occurs
|
||||||
TRequestMethod* = enum ## the used request method
|
TRequestMethod* = enum ## the used request method
|
||||||
methodNone, ## no REQUEST_METHOD environment variable
|
methodNone, ## no REQUEST_METHOD environment variable
|
||||||
methodPost, ## query uses the POST method
|
methodPost, ## query uses the POST method
|
||||||
|
|
@ -107,18 +107,18 @@ proc cgiError*(msg: string) {.noreturn.} =
|
||||||
raise e
|
raise e
|
||||||
|
|
||||||
proc getEncodedData(allowedMethods: set[TRequestMethod]): string =
|
proc getEncodedData(allowedMethods: set[TRequestMethod]): string =
|
||||||
case getenv("REQUEST_METHOD").string
|
case getEnv("REQUEST_METHOD").string
|
||||||
of "POST":
|
of "POST":
|
||||||
if methodPost notin allowedMethods:
|
if methodPost notin allowedMethods:
|
||||||
cgiError("'REQUEST_METHOD' 'POST' is not supported")
|
cgiError("'REQUEST_METHOD' 'POST' is not supported")
|
||||||
var L = parseInt(getenv("CONTENT_LENGTH").string)
|
var L = parseInt(getEnv("CONTENT_LENGTH").string)
|
||||||
result = newString(L)
|
result = newString(L)
|
||||||
if readBuffer(stdin, addr(result[0]), L) != L:
|
if readBuffer(stdin, addr(result[0]), L) != L:
|
||||||
cgiError("cannot read from stdin")
|
cgiError("cannot read from stdin")
|
||||||
of "GET":
|
of "GET":
|
||||||
if methodGet notin allowedMethods:
|
if methodGet notin allowedMethods:
|
||||||
cgiError("'REQUEST_METHOD' 'GET' is not supported")
|
cgiError("'REQUEST_METHOD' 'GET' is not supported")
|
||||||
result = getenv("QUERY_STRING").string
|
result = getEnv("QUERY_STRING").string
|
||||||
else:
|
else:
|
||||||
if methodNone notin allowedMethods:
|
if methodNone notin allowedMethods:
|
||||||
cgiError("'REQUEST_METHOD' must be 'POST' or 'GET'")
|
cgiError("'REQUEST_METHOD' must be 'POST' or 'GET'")
|
||||||
|
|
@ -192,131 +192,131 @@ proc validateData*(data: PStringTable, validKeys: varargs[string]) =
|
||||||
|
|
||||||
proc getContentLength*(): string =
|
proc getContentLength*(): string =
|
||||||
## returns contents of the ``CONTENT_LENGTH`` environment variable
|
## returns contents of the ``CONTENT_LENGTH`` environment variable
|
||||||
return getenv("CONTENT_LENGTH").string
|
return getEnv("CONTENT_LENGTH").string
|
||||||
|
|
||||||
proc getContentType*(): string =
|
proc getContentType*(): string =
|
||||||
## returns contents of the ``CONTENT_TYPE`` environment variable
|
## returns contents of the ``CONTENT_TYPE`` environment variable
|
||||||
return getenv("CONTENT_Type").string
|
return getEnv("CONTENT_Type").string
|
||||||
|
|
||||||
proc getDocumentRoot*(): string =
|
proc getDocumentRoot*(): string =
|
||||||
## returns contents of the ``DOCUMENT_ROOT`` environment variable
|
## returns contents of the ``DOCUMENT_ROOT`` environment variable
|
||||||
return getenv("DOCUMENT_ROOT").string
|
return getEnv("DOCUMENT_ROOT").string
|
||||||
|
|
||||||
proc getGatewayInterface*(): string =
|
proc getGatewayInterface*(): string =
|
||||||
## returns contents of the ``GATEWAY_INTERFACE`` environment variable
|
## returns contents of the ``GATEWAY_INTERFACE`` environment variable
|
||||||
return getenv("GATEWAY_INTERFACE").string
|
return getEnv("GATEWAY_INTERFACE").string
|
||||||
|
|
||||||
proc getHttpAccept*(): string =
|
proc getHttpAccept*(): string =
|
||||||
## returns contents of the ``HTTP_ACCEPT`` environment variable
|
## returns contents of the ``HTTP_ACCEPT`` environment variable
|
||||||
return getenv("HTTP_ACCEPT").string
|
return getEnv("HTTP_ACCEPT").string
|
||||||
|
|
||||||
proc getHttpAcceptCharset*(): string =
|
proc getHttpAcceptCharset*(): string =
|
||||||
## returns contents of the ``HTTP_ACCEPT_CHARSET`` environment variable
|
## returns contents of the ``HTTP_ACCEPT_CHARSET`` environment variable
|
||||||
return getenv("HTTP_ACCEPT_CHARSET").string
|
return getEnv("HTTP_ACCEPT_CHARSET").string
|
||||||
|
|
||||||
proc getHttpAcceptEncoding*(): string =
|
proc getHttpAcceptEncoding*(): string =
|
||||||
## returns contents of the ``HTTP_ACCEPT_ENCODING`` environment variable
|
## returns contents of the ``HTTP_ACCEPT_ENCODING`` environment variable
|
||||||
return getenv("HTTP_ACCEPT_ENCODING").string
|
return getEnv("HTTP_ACCEPT_ENCODING").string
|
||||||
|
|
||||||
proc getHttpAcceptLanguage*(): string =
|
proc getHttpAcceptLanguage*(): string =
|
||||||
## returns contents of the ``HTTP_ACCEPT_LANGUAGE`` environment variable
|
## returns contents of the ``HTTP_ACCEPT_LANGUAGE`` environment variable
|
||||||
return getenv("HTTP_ACCEPT_LANGUAGE").string
|
return getEnv("HTTP_ACCEPT_LANGUAGE").string
|
||||||
|
|
||||||
proc getHttpConnection*(): string =
|
proc getHttpConnection*(): string =
|
||||||
## returns contents of the ``HTTP_CONNECTION`` environment variable
|
## returns contents of the ``HTTP_CONNECTION`` environment variable
|
||||||
return getenv("HTTP_CONNECTION").string
|
return getEnv("HTTP_CONNECTION").string
|
||||||
|
|
||||||
proc getHttpCookie*(): string =
|
proc getHttpCookie*(): string =
|
||||||
## returns contents of the ``HTTP_COOKIE`` environment variable
|
## returns contents of the ``HTTP_COOKIE`` environment variable
|
||||||
return getenv("HTTP_COOKIE").string
|
return getEnv("HTTP_COOKIE").string
|
||||||
|
|
||||||
proc getHttpHost*(): string =
|
proc getHttpHost*(): string =
|
||||||
## returns contents of the ``HTTP_HOST`` environment variable
|
## returns contents of the ``HTTP_HOST`` environment variable
|
||||||
return getenv("HTTP_HOST").string
|
return getEnv("HTTP_HOST").string
|
||||||
|
|
||||||
proc getHttpReferer*(): string =
|
proc getHttpReferer*(): string =
|
||||||
## returns contents of the ``HTTP_REFERER`` environment variable
|
## returns contents of the ``HTTP_REFERER`` environment variable
|
||||||
return getenv("HTTP_REFERER").string
|
return getEnv("HTTP_REFERER").string
|
||||||
|
|
||||||
proc getHttpUserAgent*(): string =
|
proc getHttpUserAgent*(): string =
|
||||||
## returns contents of the ``HTTP_USER_AGENT`` environment variable
|
## returns contents of the ``HTTP_USER_AGENT`` environment variable
|
||||||
return getenv("HTTP_USER_AGENT").string
|
return getEnv("HTTP_USER_AGENT").string
|
||||||
|
|
||||||
proc getPathInfo*(): string =
|
proc getPathInfo*(): string =
|
||||||
## returns contents of the ``PATH_INFO`` environment variable
|
## returns contents of the ``PATH_INFO`` environment variable
|
||||||
return getenv("PATH_INFO").string
|
return getEnv("PATH_INFO").string
|
||||||
|
|
||||||
proc getPathTranslated*(): string =
|
proc getPathTranslated*(): string =
|
||||||
## returns contents of the ``PATH_TRANSLATED`` environment variable
|
## returns contents of the ``PATH_TRANSLATED`` environment variable
|
||||||
return getenv("PATH_TRANSLATED").string
|
return getEnv("PATH_TRANSLATED").string
|
||||||
|
|
||||||
proc getQueryString*(): string =
|
proc getQueryString*(): string =
|
||||||
## returns contents of the ``QUERY_STRING`` environment variable
|
## returns contents of the ``QUERY_STRING`` environment variable
|
||||||
return getenv("QUERY_STRING").string
|
return getEnv("QUERY_STRING").string
|
||||||
|
|
||||||
proc getRemoteAddr*(): string =
|
proc getRemoteAddr*(): string =
|
||||||
## returns contents of the ``REMOTE_ADDR`` environment variable
|
## returns contents of the ``REMOTE_ADDR`` environment variable
|
||||||
return getenv("REMOTE_ADDR").string
|
return getEnv("REMOTE_ADDR").string
|
||||||
|
|
||||||
proc getRemoteHost*(): string =
|
proc getRemoteHost*(): string =
|
||||||
## returns contents of the ``REMOTE_HOST`` environment variable
|
## returns contents of the ``REMOTE_HOST`` environment variable
|
||||||
return getenv("REMOTE_HOST").string
|
return getEnv("REMOTE_HOST").string
|
||||||
|
|
||||||
proc getRemoteIdent*(): string =
|
proc getRemoteIdent*(): string =
|
||||||
## returns contents of the ``REMOTE_IDENT`` environment variable
|
## returns contents of the ``REMOTE_IDENT`` environment variable
|
||||||
return getenv("REMOTE_IDENT").string
|
return getEnv("REMOTE_IDENT").string
|
||||||
|
|
||||||
proc getRemotePort*(): string =
|
proc getRemotePort*(): string =
|
||||||
## returns contents of the ``REMOTE_PORT`` environment variable
|
## returns contents of the ``REMOTE_PORT`` environment variable
|
||||||
return getenv("REMOTE_PORT").string
|
return getEnv("REMOTE_PORT").string
|
||||||
|
|
||||||
proc getRemoteUser*(): string =
|
proc getRemoteUser*(): string =
|
||||||
## returns contents of the ``REMOTE_USER`` environment variable
|
## returns contents of the ``REMOTE_USER`` environment variable
|
||||||
return getenv("REMOTE_USER").string
|
return getEnv("REMOTE_USER").string
|
||||||
|
|
||||||
proc getRequestMethod*(): string =
|
proc getRequestMethod*(): string =
|
||||||
## returns contents of the ``REQUEST_METHOD`` environment variable
|
## returns contents of the ``REQUEST_METHOD`` environment variable
|
||||||
return getenv("REQUEST_METHOD").string
|
return getEnv("REQUEST_METHOD").string
|
||||||
|
|
||||||
proc getRequestURI*(): string =
|
proc getRequestURI*(): string =
|
||||||
## returns contents of the ``REQUEST_URI`` environment variable
|
## returns contents of the ``REQUEST_URI`` environment variable
|
||||||
return getenv("REQUEST_URI").string
|
return getEnv("REQUEST_URI").string
|
||||||
|
|
||||||
proc getScriptFilename*(): string =
|
proc getScriptFilename*(): string =
|
||||||
## returns contents of the ``SCRIPT_FILENAME`` environment variable
|
## returns contents of the ``SCRIPT_FILENAME`` environment variable
|
||||||
return getenv("SCRIPT_FILENAME").string
|
return getEnv("SCRIPT_FILENAME").string
|
||||||
|
|
||||||
proc getScriptName*(): string =
|
proc getScriptName*(): string =
|
||||||
## returns contents of the ``SCRIPT_NAME`` environment variable
|
## returns contents of the ``SCRIPT_NAME`` environment variable
|
||||||
return getenv("SCRIPT_NAME").string
|
return getEnv("SCRIPT_NAME").string
|
||||||
|
|
||||||
proc getServerAddr*(): string =
|
proc getServerAddr*(): string =
|
||||||
## returns contents of the ``SERVER_ADDR`` environment variable
|
## returns contents of the ``SERVER_ADDR`` environment variable
|
||||||
return getenv("SERVER_ADDR").string
|
return getEnv("SERVER_ADDR").string
|
||||||
|
|
||||||
proc getServerAdmin*(): string =
|
proc getServerAdmin*(): string =
|
||||||
## returns contents of the ``SERVER_ADMIN`` environment variable
|
## returns contents of the ``SERVER_ADMIN`` environment variable
|
||||||
return getenv("SERVER_ADMIN").string
|
return getEnv("SERVER_ADMIN").string
|
||||||
|
|
||||||
proc getServerName*(): string =
|
proc getServerName*(): string =
|
||||||
## returns contents of the ``SERVER_NAME`` environment variable
|
## returns contents of the ``SERVER_NAME`` environment variable
|
||||||
return getenv("SERVER_NAME").string
|
return getEnv("SERVER_NAME").string
|
||||||
|
|
||||||
proc getServerPort*(): string =
|
proc getServerPort*(): string =
|
||||||
## returns contents of the ``SERVER_PORT`` environment variable
|
## returns contents of the ``SERVER_PORT`` environment variable
|
||||||
return getenv("SERVER_PORT").string
|
return getEnv("SERVER_PORT").string
|
||||||
|
|
||||||
proc getServerProtocol*(): string =
|
proc getServerProtocol*(): string =
|
||||||
## returns contents of the ``SERVER_PROTOCOL`` environment variable
|
## returns contents of the ``SERVER_PROTOCOL`` environment variable
|
||||||
return getenv("SERVER_PROTOCOL").string
|
return getEnv("SERVER_PROTOCOL").string
|
||||||
|
|
||||||
proc getServerSignature*(): string =
|
proc getServerSignature*(): string =
|
||||||
## returns contents of the ``SERVER_SIGNATURE`` environment variable
|
## returns contents of the ``SERVER_SIGNATURE`` environment variable
|
||||||
return getenv("SERVER_SIGNATURE").string
|
return getEnv("SERVER_SIGNATURE").string
|
||||||
|
|
||||||
proc getServerSoftware*(): string =
|
proc getServerSoftware*(): string =
|
||||||
## returns contents of the ``SERVER_SOFTWARE`` environment variable
|
## returns contents of the ``SERVER_SOFTWARE`` environment variable
|
||||||
return getenv("SERVER_SOFTWARE").string
|
return getEnv("SERVER_SOFTWARE").string
|
||||||
|
|
||||||
proc setTestData*(keysvalues: varargs[string]) =
|
proc setTestData*(keysvalues: varargs[string]) =
|
||||||
## fills the appropriate environment variables to test your CGI application.
|
## fills the appropriate environment variables to test your CGI application.
|
||||||
|
|
@ -325,7 +325,7 @@ proc setTestData*(keysvalues: varargs[string]) =
|
||||||
##
|
##
|
||||||
## .. code-block:: Nimrod
|
## .. code-block:: Nimrod
|
||||||
## setTestData("name", "Hanz", "password", "12345")
|
## setTestData("name", "Hanz", "password", "12345")
|
||||||
putenv("REQUEST_METHOD", "GET")
|
putEnv("REQUEST_METHOD", "GET")
|
||||||
var i = 0
|
var i = 0
|
||||||
var query = ""
|
var query = ""
|
||||||
while i < keysvalues.len:
|
while i < keysvalues.len:
|
||||||
|
|
@ -334,7 +334,7 @@ proc setTestData*(keysvalues: varargs[string]) =
|
||||||
add(query, URLencode(keysvalues[i+1]))
|
add(query, URLencode(keysvalues[i+1]))
|
||||||
add(query, '&')
|
add(query, '&')
|
||||||
inc(i, 2)
|
inc(i, 2)
|
||||||
putenv("QUERY_STRING", query)
|
putEnv("QUERY_STRING", query)
|
||||||
|
|
||||||
proc writeContentType*() =
|
proc writeContentType*() =
|
||||||
## call this before starting to send your HTML data to `stdout`. This
|
## call this before starting to send your HTML data to `stdout`. This
|
||||||
|
|
|
||||||
|
|
@ -129,7 +129,7 @@ proc mget*[A](s: var TSet[A], key: A): var A =
|
||||||
assert s.isValid, "The set needs to be initialized."
|
assert s.isValid, "The set needs to be initialized."
|
||||||
var index = rawGet(s, key)
|
var index = rawGet(s, key)
|
||||||
if index >= 0: result = t.data[index].key
|
if index >= 0: result = t.data[index].key
|
||||||
else: raise newException(EInvalidKey, "key not found: " & $key)
|
else: raise newException(KeyError, "key not found: " & $key)
|
||||||
|
|
||||||
proc contains*[A](s: TSet[A], key: A): bool =
|
proc contains*[A](s: TSet[A], key: A): bool =
|
||||||
## Returns true iff `key` is in `s`.
|
## Returns true iff `key` is in `s`.
|
||||||
|
|
|
||||||
|
|
@ -144,7 +144,7 @@ proc mget*[A, B](t: var TTable[A, B], key: A): var B =
|
||||||
## If `key` is not in `t`, the ``EInvalidKey`` exception is raised.
|
## 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
|
if index >= 0: result = t.data[index].val
|
||||||
else: raise newException(EInvalidKey, "key not found: " & $key)
|
else: raise newException(KeyError, "key not found: " & $key)
|
||||||
|
|
||||||
iterator allValues*[A, B](t: TTable[A, B]; key: A): B =
|
iterator allValues*[A, B](t: TTable[A, B]; key: A): B =
|
||||||
## iterates over any value in the table `t` that belongs to the given `key`.
|
## iterates over any value in the table `t` that belongs to the given `key`.
|
||||||
|
|
@ -411,7 +411,7 @@ proc mget*[A, B](t: var TOrderedTable[A, B], key: A): var B =
|
||||||
## If `key` is not in `t`, the ``EInvalidKey`` exception is raised.
|
## 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
|
if index >= 0: result = t.data[index].val
|
||||||
else: raise newException(EInvalidKey, "key not found: " & $key)
|
else: raise newException(KeyError, "key not found: " & $key)
|
||||||
|
|
||||||
proc hasKey*[A, B](t: TOrderedTable[A, B], key: A): bool =
|
proc hasKey*[A, B](t: TOrderedTable[A, B], key: A): bool =
|
||||||
## returns true iff `key` is in the table `t`.
|
## returns true iff `key` is in the table `t`.
|
||||||
|
|
@ -663,7 +663,7 @@ proc mget*[A](t: var TCountTable[A], key: A): var int =
|
||||||
## If `key` is not in `t`, the ``EInvalidKey`` exception is raised.
|
## 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
|
if index >= 0: result = t.data[index].val
|
||||||
else: raise newException(EInvalidKey, "key not found: " & $key)
|
else: raise newException(KeyError, "key not found: " & $key)
|
||||||
|
|
||||||
proc hasKey*[A](t: TCountTable[A], key: A): bool =
|
proc hasKey*[A](t: TCountTable[A], key: A): bool =
|
||||||
## returns true iff `key` is in the table `t`.
|
## returns true iff `key` is in the table `t`.
|
||||||
|
|
|
||||||
|
|
@ -47,7 +47,7 @@ proc setCookie*(key, value: string, expires: TTimeInfo,
|
||||||
## **Note:** UTC is assumed as the timezone for ``expires``.
|
## **Note:** UTC is assumed as the timezone for ``expires``.
|
||||||
|
|
||||||
return setCookie(key, value, domain, path,
|
return setCookie(key, value, domain, path,
|
||||||
format(expires, "ddd',' dd MMM yyyy HH:mm:ss 'UTC'"), noname)
|
format(expires, "ddd',' dd MMM yyyy HH:mm:ss 'UTC'"), noName)
|
||||||
|
|
||||||
when isMainModule:
|
when isMainModule:
|
||||||
var tim = TTime(int(getTime()) + 76 * (60 * 60 * 24))
|
var tim = TTime(int(getTime()) + 76 * (60 * 60 * 24))
|
||||||
|
|
|
||||||
|
|
@ -529,7 +529,7 @@ type
|
||||||
of JArray:
|
of JArray:
|
||||||
elems*: seq[PJsonNode]
|
elems*: seq[PJsonNode]
|
||||||
|
|
||||||
EJsonParsingError* = object of EInvalidValue ## is raised for a JSON error
|
EJsonParsingError* = object of ValueError ## is raised for a JSON error
|
||||||
|
|
||||||
proc raiseParseErr*(p: TJsonParser, msg: string) {.noinline, noreturn.} =
|
proc raiseParseErr*(p: TJsonParser, msg: string) {.noinline, noreturn.} =
|
||||||
## raises an `EJsonParsingError` exception.
|
## raises an `EJsonParsingError` exception.
|
||||||
|
|
@ -741,7 +741,7 @@ proc delete*(obj: PJsonNode, key: string) =
|
||||||
if obj.fields[i].key == key:
|
if obj.fields[i].key == key:
|
||||||
obj.fields.delete(i)
|
obj.fields.delete(i)
|
||||||
return
|
return
|
||||||
raise newException(EInvalidIndex, "key not in object")
|
raise newException(IndexError, "key not in object")
|
||||||
|
|
||||||
proc copy*(p: PJsonNode): PJsonNode =
|
proc copy*(p: PJsonNode): PJsonNode =
|
||||||
## Performs a deep copy of `a`.
|
## Performs a deep copy of `a`.
|
||||||
|
|
@ -942,7 +942,7 @@ when not defined(js):
|
||||||
## Parses `file` into a `PJsonNode`.
|
## Parses `file` into a `PJsonNode`.
|
||||||
var stream = newFileStream(filename, fmRead)
|
var stream = newFileStream(filename, fmRead)
|
||||||
if stream == nil:
|
if stream == nil:
|
||||||
raise newException(EIO, "cannot read from file: " & filename)
|
raise newException(IOError, "cannot read from file: " & filename)
|
||||||
result = parseJson(stream, filename)
|
result = parseJson(stream, filename)
|
||||||
else:
|
else:
|
||||||
from math import `mod`
|
from math import `mod`
|
||||||
|
|
|
||||||
|
|
@ -25,7 +25,7 @@ const
|
||||||
#
|
#
|
||||||
|
|
||||||
type
|
type
|
||||||
TBaseLexer* = object of TObject ## the base lexer. Inherit your lexer from
|
TBaseLexer* = object of RootObj ## the base lexer. Inherit your lexer from
|
||||||
## this object.
|
## this object.
|
||||||
bufpos*: int ## the current position within the buffer
|
bufpos*: int ## the current position within the buffer
|
||||||
buf*: cstring ## the buffer itself
|
buf*: cstring ## the buffer itself
|
||||||
|
|
|
||||||
|
|
@ -278,11 +278,11 @@ else:
|
||||||
proc `mod`*(x, y: float): float =
|
proc `mod`*(x, y: float): float =
|
||||||
result = if y == 0.0: x else: x - y * (x/y).floor
|
result = if y == 0.0: x else: x - y * (x/y).floor
|
||||||
|
|
||||||
proc random*[T](x: TSlice[T]): T =
|
proc random*[T](x: Slice[T]): T =
|
||||||
## For a slice `a .. b` returns a value in the range `a .. b-1`.
|
## For a slice `a .. b` returns a value in the range `a .. b-1`.
|
||||||
result = random(x.b - x.a) + x.a
|
result = random(x.b - x.a) + x.a
|
||||||
|
|
||||||
proc random[T](a: openarray[T]): T =
|
proc random[T](a: openArray[T]): T =
|
||||||
## returns a random element from the openarray `a`.
|
## returns a random element from the openarray `a`.
|
||||||
result = a[random(a.low..a.len)]
|
result = a[random(a.low..a.len)]
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -35,7 +35,7 @@ type
|
||||||
handle: cint
|
handle: cint
|
||||||
|
|
||||||
|
|
||||||
proc mapMem*(m: var TMemFile, mode: TFileMode = fmRead,
|
proc mapMem*(m: var TMemFile, mode: FileMode = fmRead,
|
||||||
mappedSize = -1, offset = 0): pointer =
|
mappedSize = -1, offset = 0): pointer =
|
||||||
var readonly = mode == fmRead
|
var readonly = mode == fmRead
|
||||||
when defined(windows):
|
when defined(windows):
|
||||||
|
|
@ -71,7 +71,7 @@ proc unmapMem*(f: var TMemFile, p: pointer, size: int) =
|
||||||
if munmap(p, size) != 0: osError(osLastError())
|
if munmap(p, size) != 0: osError(osLastError())
|
||||||
|
|
||||||
|
|
||||||
proc open*(filename: string, mode: TFileMode = fmRead,
|
proc open*(filename: string, mode: FileMode = fmRead,
|
||||||
mappedSize = -1, offset = 0, newFileSize = -1): TMemFile =
|
mappedSize = -1, offset = 0, newFileSize = -1): TMemFile =
|
||||||
## opens a memory mapped file. If this fails, ``EOS`` is raised.
|
## opens a memory mapped file. If this fails, ``EOS`` is raised.
|
||||||
## `newFileSize` can only be set if the file does not exist and is opened
|
## `newFileSize` can only be set if the file does not exist and is opened
|
||||||
|
|
|
||||||
|
|
@ -29,14 +29,14 @@ else:
|
||||||
include "system/ansi_c"
|
include "system/ansi_c"
|
||||||
|
|
||||||
type
|
type
|
||||||
FReadEnv* = object of FReadIO ## effect that denotes a read
|
FReadEnv* = object of ReadIOEffect ## effect that denotes a read
|
||||||
## from an environment variable
|
## from an environment variable
|
||||||
FWriteEnv* = object of FWriteIO ## effect that denotes a write
|
FWriteEnv* = object of WriteIOEffect ## effect that denotes a write
|
||||||
## to an environment variable
|
## to an environment variable
|
||||||
|
|
||||||
FReadDir* = object of FReadIO ## effect that denotes a write operation to
|
FReadDir* = object of ReadIOEffect ## effect that denotes a write operation to
|
||||||
## the directory structure
|
## the directory structure
|
||||||
FWriteDir* = object of FWriteIO ## effect that denotes a write operation to
|
FWriteDir* = object of WriteIOEffect ## effect that denotes a write operation to
|
||||||
## the directory structure
|
## the directory structure
|
||||||
|
|
||||||
TOSErrorCode* = distinct int32 ## Specifies an OS Error Code.
|
TOSErrorCode* = distinct int32 ## Specifies an OS Error Code.
|
||||||
|
|
@ -214,9 +214,9 @@ proc osError*(msg: string = "") {.noinline, rtl, extern: "nos$1", deprecated.} =
|
||||||
## **Deprecated since version 0.9.4**: use the other ``OSError`` proc.
|
## **Deprecated since version 0.9.4**: use the other ``OSError`` proc.
|
||||||
if len(msg) == 0:
|
if len(msg) == 0:
|
||||||
var m = osErrorMsg()
|
var m = osErrorMsg()
|
||||||
raise newException(EOS, if m.len > 0: m else: "unknown OS error")
|
raise newException(OSError, if m.len > 0: m else: "unknown OS error")
|
||||||
else:
|
else:
|
||||||
raise newException(EOS, msg)
|
raise newException(OSError, msg)
|
||||||
{.pop.}
|
{.pop.}
|
||||||
|
|
||||||
proc `==`*(err1, err2: TOSErrorCode): bool {.borrow.}
|
proc `==`*(err1, err2: TOSErrorCode): bool {.borrow.}
|
||||||
|
|
@ -260,7 +260,7 @@ proc osError*(errorCode: TOSErrorCode) =
|
||||||
##
|
##
|
||||||
## If the error code is ``0`` or an error message could not be retrieved,
|
## If the error code is ``0`` or an error message could not be retrieved,
|
||||||
## the message ``unknown OS error`` will be used.
|
## the message ``unknown OS error`` will be used.
|
||||||
var e: ref EOS; new(e)
|
var e: ref OSError; new(e)
|
||||||
e.errorCode = errorCode.int32
|
e.errorCode = errorCode.int32
|
||||||
e.msg = osErrorMsg(errorCode)
|
e.msg = osErrorMsg(errorCode)
|
||||||
if e.msg == "":
|
if e.msg == "":
|
||||||
|
|
@ -840,13 +840,13 @@ proc sameFile*(path1, path2: string): bool {.rtl, extern: "nos$1",
|
||||||
result = a.st_dev == b.st_dev and a.st_ino == b.st_ino
|
result = a.st_dev == b.st_dev and a.st_ino == b.st_ino
|
||||||
|
|
||||||
proc sameFileContent*(path1, path2: string): bool {.rtl, extern: "nos$1",
|
proc sameFileContent*(path1, path2: string): bool {.rtl, extern: "nos$1",
|
||||||
tags: [FReadIO].} =
|
tags: [ReadIOEffect].} =
|
||||||
## Returns True if both pathname arguments refer to files with identical
|
## Returns True if both pathname arguments refer to files with identical
|
||||||
## binary content.
|
## binary content.
|
||||||
const
|
const
|
||||||
bufSize = 8192 # 8K buffer
|
bufSize = 8192 # 8K buffer
|
||||||
var
|
var
|
||||||
a, b: TFile
|
a, b: File
|
||||||
if not open(a, path1): return false
|
if not open(a, path1): return false
|
||||||
if not open(b, path2):
|
if not open(b, path2):
|
||||||
close(a)
|
close(a)
|
||||||
|
|
@ -951,7 +951,7 @@ proc setFilePermissions*(filename: string, permissions: set[TFilePermission]) {.
|
||||||
if res2 == - 1'i32: osError(osLastError())
|
if res2 == - 1'i32: osError(osLastError())
|
||||||
|
|
||||||
proc copyFile*(source, dest: string) {.rtl, extern: "nos$1",
|
proc copyFile*(source, dest: string) {.rtl, extern: "nos$1",
|
||||||
tags: [FReadIO, FWriteIO].} =
|
tags: [ReadIOEffect, FWriteIO].} =
|
||||||
## Copies a file from `source` to `dest`.
|
## Copies a file from `source` to `dest`.
|
||||||
##
|
##
|
||||||
## If this fails, `EOS` is raised. On the Windows platform this proc will
|
## If this fails, `EOS` is raised. On the Windows platform this proc will
|
||||||
|
|
@ -993,10 +993,10 @@ proc copyFile*(source, dest: string) {.rtl, extern: "nos$1",
|
||||||
close(d)
|
close(d)
|
||||||
|
|
||||||
proc moveFile*(source, dest: string) {.rtl, extern: "nos$1",
|
proc moveFile*(source, dest: string) {.rtl, extern: "nos$1",
|
||||||
tags: [FReadIO, FWriteIO].} =
|
tags: [ReadIOEffect, FWriteIO].} =
|
||||||
## Moves a file from `source` to `dest`. If this fails, `EOS` is raised.
|
## Moves a file from `source` to `dest`. If this fails, `EOS` is raised.
|
||||||
if c_rename(source, dest) != 0'i32:
|
if c_rename(source, dest) != 0'i32:
|
||||||
raise newException(EOS, $strerror(errno))
|
raise newException(OSError, $strerror(errno))
|
||||||
|
|
||||||
when not declared(ENOENT) and not defined(Windows):
|
when not declared(ENOENT) and not defined(Windows):
|
||||||
when NoFakeVars:
|
when NoFakeVars:
|
||||||
|
|
@ -1034,7 +1034,7 @@ proc removeFile*(file: string) {.rtl, extern: "nos$1", tags: [FWriteDir].} =
|
||||||
raise newException(EOS, $strerror(errno))
|
raise newException(EOS, $strerror(errno))
|
||||||
|
|
||||||
proc execShellCmd*(command: string): int {.rtl, extern: "nos$1",
|
proc execShellCmd*(command: string): int {.rtl, extern: "nos$1",
|
||||||
tags: [FExecIO].} =
|
tags: [ExecIOEffect].} =
|
||||||
## Executes a `shell command`:idx:.
|
## Executes a `shell command`:idx:.
|
||||||
##
|
##
|
||||||
## Command has the form 'program args' where args are the command
|
## Command has the form 'program args' where args are the command
|
||||||
|
|
@ -1076,7 +1076,7 @@ when defined(windows):
|
||||||
while true:
|
while true:
|
||||||
var eend = strEnd(e)
|
var eend = strEnd(e)
|
||||||
add(environment, $e)
|
add(environment, $e)
|
||||||
e = cast[WideCString](cast[TAddress](eend)+2)
|
e = cast[WideCString](cast[ByteAddress](eend)+2)
|
||||||
if eend[1].int == 0: break
|
if eend[1].int == 0: break
|
||||||
discard freeEnvironmentStringsW(env)
|
discard freeEnvironmentStringsW(env)
|
||||||
else:
|
else:
|
||||||
|
|
@ -1364,7 +1364,7 @@ proc createDir*(dir: string) {.rtl, extern: "nos$1", tags: [FWriteDir].} =
|
||||||
rawCreateDir(dir)
|
rawCreateDir(dir)
|
||||||
|
|
||||||
proc copyDir*(source, dest: string) {.rtl, extern: "nos$1",
|
proc copyDir*(source, dest: string) {.rtl, extern: "nos$1",
|
||||||
tags: [FWriteIO, FReadIO].} =
|
tags: [WriteIOEffect, FReadIO].} =
|
||||||
## Copies a directory from `source` to `dest`.
|
## Copies a directory from `source` to `dest`.
|
||||||
##
|
##
|
||||||
## If this fails, `EOS` is raised. On the Windows platform this proc will
|
## If this fails, `EOS` is raised. On the Windows platform this proc will
|
||||||
|
|
@ -1537,7 +1537,7 @@ proc copyFileWithPermissions*(source, dest: string,
|
||||||
|
|
||||||
proc copyDirWithPermissions*(source, dest: string,
|
proc copyDirWithPermissions*(source, dest: string,
|
||||||
ignorePermissionErrors = true) {.rtl, extern: "nos$1",
|
ignorePermissionErrors = true) {.rtl, extern: "nos$1",
|
||||||
tags: [FWriteIO, FReadIO].} =
|
tags: [WriteIOEffect, FReadIO].} =
|
||||||
## Copies a directory from `source` to `dest` preserving file permissions.
|
## Copies a directory from `source` to `dest` preserving file permissions.
|
||||||
##
|
##
|
||||||
## If this fails, `EOS` is raised. This is a wrapper proc around `copyDir()
|
## If this fails, `EOS` is raised. This is a wrapper proc around `copyDir()
|
||||||
|
|
@ -1657,13 +1657,13 @@ elif defined(windows):
|
||||||
var
|
var
|
||||||
ownArgv {.threadvar.}: seq[string]
|
ownArgv {.threadvar.}: seq[string]
|
||||||
|
|
||||||
proc paramCount*(): int {.rtl, extern: "nos$1", tags: [FReadIO].} =
|
proc paramCount*(): int {.rtl, extern: "nos$1", tags: [ReadIOEffect].} =
|
||||||
# Docstring in nimdoc block.
|
# Docstring in nimdoc block.
|
||||||
if isNil(ownArgv): ownArgv = parseCmdLine($getCommandLine())
|
if isNil(ownArgv): ownArgv = parseCmdLine($getCommandLine())
|
||||||
result = ownArgv.len-1
|
result = ownArgv.len-1
|
||||||
|
|
||||||
proc paramStr*(i: int): TaintedString {.rtl, extern: "nos$1",
|
proc paramStr*(i: int): TaintedString {.rtl, extern: "nos$1",
|
||||||
tags: [FReadIO].} =
|
tags: [ReadIOEffect].} =
|
||||||
# Docstring in nimdoc block.
|
# Docstring in nimdoc block.
|
||||||
if isNil(ownArgv): ownArgv = parseCmdLine($getCommandLine())
|
if isNil(ownArgv): ownArgv = parseCmdLine($getCommandLine())
|
||||||
return TaintedString(ownArgv[i])
|
return TaintedString(ownArgv[i])
|
||||||
|
|
@ -1739,7 +1739,7 @@ when defined(macosx):
|
||||||
proc getExecPath2(c: cstring, size: var cuint32): bool {.
|
proc getExecPath2(c: cstring, size: var cuint32): bool {.
|
||||||
importc: "_NSGetExecutablePath", header: "<mach-o/dyld.h>".}
|
importc: "_NSGetExecutablePath", header: "<mach-o/dyld.h>".}
|
||||||
|
|
||||||
proc getAppFilename*(): string {.rtl, extern: "nos$1", tags: [FReadIO].} =
|
proc getAppFilename*(): string {.rtl, extern: "nos$1", tags: [ReadIOEffect].} =
|
||||||
## Returns the filename of the application's executable.
|
## Returns the filename of the application's executable.
|
||||||
##
|
##
|
||||||
## This procedure will resolve symlinks.
|
## This procedure will resolve symlinks.
|
||||||
|
|
@ -1795,12 +1795,12 @@ proc getApplicationDir*(): string {.rtl, extern: "nos$1", deprecated.} =
|
||||||
## instead.
|
## instead.
|
||||||
result = splitFile(getAppFilename()).dir
|
result = splitFile(getAppFilename()).dir
|
||||||
|
|
||||||
proc getAppDir*(): string {.rtl, extern: "nos$1", tags: [FReadIO].} =
|
proc getAppDir*(): string {.rtl, extern: "nos$1", tags: [ReadIOEffect].} =
|
||||||
## Returns the directory of the application's executable.
|
## Returns the directory of the application's executable.
|
||||||
## **Note**: This does not work reliably on BSD.
|
## **Note**: This does not work reliably on BSD.
|
||||||
result = splitFile(getAppFilename()).dir
|
result = splitFile(getAppFilename()).dir
|
||||||
|
|
||||||
proc sleep*(milsecs: int) {.rtl, extern: "nos$1", tags: [FTime].} =
|
proc sleep*(milsecs: int) {.rtl, extern: "nos$1", tags: [TimeEffect].} =
|
||||||
## sleeps `milsecs` milliseconds.
|
## sleeps `milsecs` milliseconds.
|
||||||
when defined(windows):
|
when defined(windows):
|
||||||
winlean.sleep(int32(milsecs))
|
winlean.sleep(int32(milsecs))
|
||||||
|
|
@ -1811,7 +1811,7 @@ proc sleep*(milsecs: int) {.rtl, extern: "nos$1", tags: [FTime].} =
|
||||||
discard posix.nanosleep(a, b)
|
discard posix.nanosleep(a, b)
|
||||||
|
|
||||||
proc getFileSize*(file: string): BiggestInt {.rtl, extern: "nos$1",
|
proc getFileSize*(file: string): BiggestInt {.rtl, extern: "nos$1",
|
||||||
tags: [FReadIO].} =
|
tags: [ReadIOEffect].} =
|
||||||
## returns the file size of `file`. Can raise ``EOS``.
|
## returns the file size of `file`. Can raise ``EOS``.
|
||||||
when defined(windows):
|
when defined(windows):
|
||||||
var a: TWIN32_FIND_DATA
|
var a: TWIN32_FIND_DATA
|
||||||
|
|
@ -1939,7 +1939,7 @@ template rawToFormalFileInfo(rawInfo, formalInfo): expr =
|
||||||
if S_ISDIR(rawInfo.st_mode): formalInfo.kind = pcDir
|
if S_ISDIR(rawInfo.st_mode): formalInfo.kind = pcDir
|
||||||
if S_ISLNK(rawInfo.st_mode): formalInfo.kind.inc()
|
if S_ISLNK(rawInfo.st_mode): formalInfo.kind.inc()
|
||||||
|
|
||||||
proc getFileInfo*(handle: TFileHandle): FileInfo =
|
proc getFileInfo*(handle: FileHandle): FileInfo =
|
||||||
## Retrieves file information for the file object represented by the given
|
## Retrieves file information for the file object represented by the given
|
||||||
## handle.
|
## handle.
|
||||||
##
|
##
|
||||||
|
|
@ -1960,7 +1960,7 @@ proc getFileInfo*(handle: TFileHandle): FileInfo =
|
||||||
osError(osLastError())
|
osError(osLastError())
|
||||||
rawToFormalFileInfo(rawInfo, result)
|
rawToFormalFileInfo(rawInfo, result)
|
||||||
|
|
||||||
proc getFileInfo*(file: TFile): FileInfo =
|
proc getFileInfo*(file: File): FileInfo =
|
||||||
result = getFileInfo(file.fileHandle())
|
result = getFileInfo(file.fileHandle())
|
||||||
|
|
||||||
proc getFileInfo*(path: string, followSymlink = true): FileInfo =
|
proc getFileInfo*(path: string, followSymlink = true): FileInfo =
|
||||||
|
|
|
||||||
|
|
@ -24,10 +24,10 @@ when defined(linux):
|
||||||
import linux
|
import linux
|
||||||
|
|
||||||
type
|
type
|
||||||
TProcess = object of TObject
|
TProcess = object of RootObj
|
||||||
when defined(windows):
|
when defined(windows):
|
||||||
fProcessHandle: THandle
|
fProcessHandle: THandle
|
||||||
inHandle, outHandle, errHandle: TFileHandle
|
inHandle, outHandle, errHandle: FileHandle
|
||||||
id: THandle
|
id: THandle
|
||||||
else:
|
else:
|
||||||
inHandle, outHandle, errHandle: TFileHandle
|
inHandle, outHandle, errHandle: TFileHandle
|
||||||
|
|
@ -103,19 +103,19 @@ proc quoteShell*(s: string): string {.noSideEffect, rtl, extern: "nosp$1".} =
|
||||||
{.error:"quoteShell is not supported on your system".}
|
{.error:"quoteShell is not supported on your system".}
|
||||||
|
|
||||||
proc execProcess*(command: string,
|
proc execProcess*(command: string,
|
||||||
args: openarray[string] = [],
|
args: openArray[string] = [],
|
||||||
env: PStringTable = nil,
|
env: PStringTable = nil,
|
||||||
options: set[TProcessOption] = {poStdErrToStdOut,
|
options: set[TProcessOption] = {poStdErrToStdOut,
|
||||||
poUsePath,
|
poUsePath,
|
||||||
poEvalCommand}): TaintedString {.
|
poEvalCommand}): TaintedString {.
|
||||||
rtl, extern: "nosp$1",
|
rtl, extern: "nosp$1",
|
||||||
tags: [FExecIO, FReadIO].}
|
tags: [ExecIOEffect, FReadIO].}
|
||||||
## A convenience procedure that executes ``command`` with ``startProcess``
|
## A convenience procedure that executes ``command`` with ``startProcess``
|
||||||
## and returns its output as a string.
|
## and returns its output as a string.
|
||||||
## WARNING: this function uses poEvalCommand by default for backward compatibility.
|
## WARNING: this function uses poEvalCommand by default for backward compatibility.
|
||||||
## Make sure to pass options explicitly.
|
## Make sure to pass options explicitly.
|
||||||
|
|
||||||
proc execCmd*(command: string): int {.rtl, extern: "nosp$1", tags: [FExecIO].}
|
proc execCmd*(command: string): int {.rtl, extern: "nosp$1", tags: [ExecIOEffect].}
|
||||||
## Executes ``command`` and returns its error code. Standard input, output,
|
## Executes ``command`` and returns its error code. Standard input, output,
|
||||||
## error streams are inherited from the calling process. This operation
|
## error streams are inherited from the calling process. This operation
|
||||||
## is also often called `system`:idx:.
|
## is also often called `system`:idx:.
|
||||||
|
|
@ -125,7 +125,7 @@ proc startProcess*(command: string,
|
||||||
args: openArray[string] = [],
|
args: openArray[string] = [],
|
||||||
env: PStringTable = nil,
|
env: PStringTable = nil,
|
||||||
options: set[TProcessOption] = {poStdErrToStdOut}):
|
options: set[TProcessOption] = {poStdErrToStdOut}):
|
||||||
PProcess {.rtl, extern: "nosp$1", tags: [FExecIO, FReadEnv].}
|
PProcess {.rtl, extern: "nosp$1", tags: [ExecIOEffect, FReadEnv].}
|
||||||
## Starts a process. `Command` is the executable file, `workingDir` is the
|
## Starts a process. `Command` is the executable file, `workingDir` is the
|
||||||
## process's working directory. If ``workingDir == ""`` the current directory
|
## process's working directory. If ``workingDir == ""`` the current directory
|
||||||
## is used. `args` are the command line arguments that are passed to the
|
## is used. `args` are the command line arguments that are passed to the
|
||||||
|
|
@ -150,7 +150,7 @@ proc startProcess*(command: string,
|
||||||
|
|
||||||
proc startCmd*(command: string, options: set[TProcessOption] = {
|
proc startCmd*(command: string, options: set[TProcessOption] = {
|
||||||
poStdErrToStdOut, poUsePath}): PProcess {.
|
poStdErrToStdOut, poUsePath}): PProcess {.
|
||||||
tags: [FExecIO, FReadEnv], deprecated.} =
|
tags: [ExecIOEffect, FReadEnv], deprecated.} =
|
||||||
## Deprecated - use `startProcess` directly.
|
## Deprecated - use `startProcess` directly.
|
||||||
result = startProcess(command=command, options=options + {poEvalCommand})
|
result = startProcess(command=command, options=options + {poEvalCommand})
|
||||||
|
|
||||||
|
|
@ -201,7 +201,7 @@ proc errorStream*(p: PProcess): PStream {.rtl, extern: "nosp$1", tags: [].}
|
||||||
## **Warning**: The returned `PStream` should not be closed manually as it
|
## **Warning**: The returned `PStream` should not be closed manually as it
|
||||||
## is closed when closing the PProcess ``p``.
|
## is closed when closing the PProcess ``p``.
|
||||||
|
|
||||||
proc inputHandle*(p: PProcess): TFileHandle {.rtl, extern: "nosp$1",
|
proc inputHandle*(p: PProcess): FileHandle {.rtl, extern: "nosp$1",
|
||||||
tags: [].} =
|
tags: [].} =
|
||||||
## returns ``p``'s input file handle for writing to.
|
## returns ``p``'s input file handle for writing to.
|
||||||
##
|
##
|
||||||
|
|
@ -209,7 +209,7 @@ proc inputHandle*(p: PProcess): TFileHandle {.rtl, extern: "nosp$1",
|
||||||
## it is closed when closing the PProcess ``p``.
|
## it is closed when closing the PProcess ``p``.
|
||||||
result = p.inHandle
|
result = p.inHandle
|
||||||
|
|
||||||
proc outputHandle*(p: PProcess): TFileHandle {.rtl, extern: "nosp$1",
|
proc outputHandle*(p: PProcess): FileHandle {.rtl, extern: "nosp$1",
|
||||||
tags: [].} =
|
tags: [].} =
|
||||||
## returns ``p``'s output file handle for reading from.
|
## returns ``p``'s output file handle for reading from.
|
||||||
##
|
##
|
||||||
|
|
@ -217,7 +217,7 @@ proc outputHandle*(p: PProcess): TFileHandle {.rtl, extern: "nosp$1",
|
||||||
## it is closed when closing the PProcess ``p``.
|
## it is closed when closing the PProcess ``p``.
|
||||||
result = p.outHandle
|
result = p.outHandle
|
||||||
|
|
||||||
proc errorHandle*(p: PProcess): TFileHandle {.rtl, extern: "nosp$1",
|
proc errorHandle*(p: PProcess): FileHandle {.rtl, extern: "nosp$1",
|
||||||
tags: [].} =
|
tags: [].} =
|
||||||
## returns ``p``'s error file handle for reading from.
|
## returns ``p``'s error file handle for reading from.
|
||||||
##
|
##
|
||||||
|
|
@ -233,7 +233,7 @@ proc countProcessors*(): int {.rtl, extern: "nosp$1".} =
|
||||||
proc execProcesses*(cmds: openArray[string],
|
proc execProcesses*(cmds: openArray[string],
|
||||||
options = {poStdErrToStdOut, poParentStreams},
|
options = {poStdErrToStdOut, poParentStreams},
|
||||||
n = countProcessors()): int {.rtl, extern: "nosp$1",
|
n = countProcessors()): int {.rtl, extern: "nosp$1",
|
||||||
tags: [FExecIO, FTime, FReadEnv]} =
|
tags: [ExecIOEffect, FTime, FReadEnv]} =
|
||||||
## executes the commands `cmds` in parallel. Creates `n` processes
|
## executes the commands `cmds` in parallel. Creates `n` processes
|
||||||
## that execute in parallel. The highest return value of all processes
|
## that execute in parallel. The highest return value of all processes
|
||||||
## is returned.
|
## is returned.
|
||||||
|
|
@ -294,7 +294,7 @@ proc select*(readfds: var seq[PProcess], timeout = 500): int
|
||||||
|
|
||||||
when not defined(useNimRtl):
|
when not defined(useNimRtl):
|
||||||
proc execProcess(command: string,
|
proc execProcess(command: string,
|
||||||
args: openarray[string] = [],
|
args: openArray[string] = [],
|
||||||
env: PStringTable = nil,
|
env: PStringTable = nil,
|
||||||
options: set[TProcessOption] = {poStdErrToStdOut,
|
options: set[TProcessOption] = {poStdErrToStdOut,
|
||||||
poUsePath,
|
poUsePath,
|
||||||
|
|
@ -406,16 +406,16 @@ when defined(Windows) and not defined(useNimRtl):
|
||||||
he = ho
|
he = ho
|
||||||
else:
|
else:
|
||||||
createPipeHandles(he, si.hStdError)
|
createPipeHandles(he, si.hStdError)
|
||||||
result.inHandle = TFileHandle(hi)
|
result.inHandle = FileHandle(hi)
|
||||||
result.outHandle = TFileHandle(ho)
|
result.outHandle = FileHandle(ho)
|
||||||
result.errHandle = TFileHandle(he)
|
result.errHandle = FileHandle(he)
|
||||||
else:
|
else:
|
||||||
si.hStdError = getStdHandle(STD_ERROR_HANDLE)
|
si.hStdError = getStdHandle(STD_ERROR_HANDLE)
|
||||||
si.hStdInput = getStdHandle(STD_INPUT_HANDLE)
|
si.hStdInput = getStdHandle(STD_INPUT_HANDLE)
|
||||||
si.hStdOutput = getStdHandle(STD_OUTPUT_HANDLE)
|
si.hStdOutput = getStdHandle(STD_OUTPUT_HANDLE)
|
||||||
result.inHandle = TFileHandle(si.hStdInput)
|
result.inHandle = FileHandle(si.hStdInput)
|
||||||
result.outHandle = TFileHandle(si.hStdOutput)
|
result.outHandle = FileHandle(si.hStdOutput)
|
||||||
result.errHandle = TFileHandle(si.hStdError)
|
result.errHandle = FileHandle(si.hStdError)
|
||||||
|
|
||||||
var cmdl: cstring
|
var cmdl: cstring
|
||||||
if poEvalCommand in options:
|
if poEvalCommand in options:
|
||||||
|
|
@ -916,7 +916,7 @@ elif not defined(useNimRtl):
|
||||||
proc execCmdEx*(command: string, options: set[TProcessOption] = {
|
proc execCmdEx*(command: string, options: set[TProcessOption] = {
|
||||||
poStdErrToStdOut, poUsePath}): tuple[
|
poStdErrToStdOut, poUsePath}): tuple[
|
||||||
output: TaintedString,
|
output: TaintedString,
|
||||||
exitCode: int] {.tags: [FExecIO, FReadIO], gcsafe.} =
|
exitCode: int] {.tags: [ExecIOEffect, FReadIO], gcsafe.} =
|
||||||
## a convenience proc that runs the `command`, grabs all its output and
|
## a convenience proc that runs the `command`, grabs all its output and
|
||||||
## exit code and returns both.
|
## exit code and returns both.
|
||||||
var p = startCmd(command, options)
|
var p = startCmd(command, options)
|
||||||
|
|
|
||||||
|
|
@ -28,7 +28,7 @@ type
|
||||||
cmdLongoption, ## a long option ``--option`` detected
|
cmdLongoption, ## a long option ``--option`` detected
|
||||||
cmdShortOption ## a short option ``-c`` detected
|
cmdShortOption ## a short option ``-c`` detected
|
||||||
TOptParser* =
|
TOptParser* =
|
||||||
object of TObject ## this object implements the command line parser
|
object of RootObj ## this object implements the command line parser
|
||||||
cmd: string
|
cmd: string
|
||||||
pos: int
|
pos: int
|
||||||
inShortState: bool
|
inShortState: bool
|
||||||
|
|
|
||||||
|
|
@ -227,7 +227,7 @@ proc parseInt*(s: string, number: var int, start = 0): int {.
|
||||||
result = parseBiggestInt(s, res, start)
|
result = parseBiggestInt(s, res, start)
|
||||||
if (sizeof(int) <= 4) and
|
if (sizeof(int) <= 4) and
|
||||||
((res < low(int)) or (res > high(int))):
|
((res < low(int)) or (res > high(int))):
|
||||||
raise newException(EOverflow, "overflow")
|
raise newException(OverflowError, "overflow")
|
||||||
else:
|
else:
|
||||||
number = int(res)
|
number = int(res)
|
||||||
|
|
||||||
|
|
@ -376,7 +376,7 @@ iterator interpolatedFragments*(s: string): tuple[kind: TInterpolatedKind,
|
||||||
break
|
break
|
||||||
dec nesting
|
dec nesting
|
||||||
of '\0':
|
of '\0':
|
||||||
raise newException(EInvalidValue,
|
raise newException(ValueError,
|
||||||
"Expected closing '}': " & s[i..s.len])
|
"Expected closing '}': " & s[i..s.len])
|
||||||
else: discard
|
else: discard
|
||||||
inc j
|
inc j
|
||||||
|
|
@ -392,7 +392,7 @@ iterator interpolatedFragments*(s: string): tuple[kind: TInterpolatedKind,
|
||||||
inc i # skip $
|
inc i # skip $
|
||||||
kind = ikDollar
|
kind = ikDollar
|
||||||
else:
|
else:
|
||||||
raise newException(EInvalidValue,
|
raise newException(ValueError,
|
||||||
"Unable to parse a varible name at " & s[i..s.len])
|
"Unable to parse a varible name at " & s[i..s.len])
|
||||||
else:
|
else:
|
||||||
while j < s.len and s[j] != '$': inc j
|
while j < s.len and s[j] != '$': inc j
|
||||||
|
|
|
||||||
|
|
@ -377,14 +377,14 @@ proc socketError*(socket: TSocket, err: int = -1, async = false) =
|
||||||
else: osError(lastError)
|
else: osError(lastError)
|
||||||
else: osError(lastError)
|
else: osError(lastError)
|
||||||
|
|
||||||
proc listen*(socket: TSocket, backlog = SOMAXCONN) {.tags: [FReadIO].} =
|
proc listen*(socket: TSocket, backlog = SOMAXCONN) {.tags: [ReadIOEffect].} =
|
||||||
## Marks ``socket`` as accepting connections.
|
## Marks ``socket`` as accepting connections.
|
||||||
## ``Backlog`` specifies the maximum length of the
|
## ``Backlog`` specifies the maximum length of the
|
||||||
## queue of pending connections.
|
## queue of pending connections.
|
||||||
if listen(socket.fd, cint(backlog)) < 0'i32: osError(osLastError())
|
if listen(socket.fd, cint(backlog)) < 0'i32: osError(osLastError())
|
||||||
|
|
||||||
proc invalidIp4(s: string) {.noreturn, noinline.} =
|
proc invalidIp4(s: string) {.noreturn, noinline.} =
|
||||||
raise newException(EInvalidValue, "invalid ip4 address: " & s)
|
raise newException(ValueError, "invalid ip4 address: " & s)
|
||||||
|
|
||||||
proc parseIp4*(s: string): BiggestInt =
|
proc parseIp4*(s: string): BiggestInt =
|
||||||
## parses an IP version 4 in dotted decimal form like "a.b.c.d".
|
## parses an IP version 4 in dotted decimal form like "a.b.c.d".
|
||||||
|
|
@ -422,10 +422,10 @@ template gaiNim(a, p, h, list: expr): stmt =
|
||||||
when defined(windows):
|
when defined(windows):
|
||||||
osError(osLastError())
|
osError(osLastError())
|
||||||
else:
|
else:
|
||||||
raise newException(EOS, $gai_strerror(gaiResult))
|
raise newException(OSError, $gai_strerror(gaiResult))
|
||||||
|
|
||||||
proc bindAddr*(socket: TSocket, port = TPort(0), address = "") {.
|
proc bindAddr*(socket: TSocket, port = TPort(0), address = "") {.
|
||||||
tags: [FReadIO].} =
|
tags: [ReadIOEffect].} =
|
||||||
## binds an address/port number to a socket.
|
## binds an address/port number to a socket.
|
||||||
## Use address string in dotted decimal form like "a.b.c.d"
|
## Use address string in dotted decimal form like "a.b.c.d"
|
||||||
## or leave "" for any address.
|
## or leave "" for any address.
|
||||||
|
|
@ -439,16 +439,16 @@ proc bindAddr*(socket: TSocket, port = TPort(0), address = "") {.
|
||||||
name.sin_port = sockets.htons(int16(port))
|
name.sin_port = sockets.htons(int16(port))
|
||||||
name.sin_addr.s_addr = sockets.htonl(INADDR_ANY)
|
name.sin_addr.s_addr = sockets.htonl(INADDR_ANY)
|
||||||
if bindSocket(socket.fd, cast[ptr TSockAddr](addr(name)),
|
if bindSocket(socket.fd, cast[ptr TSockAddr](addr(name)),
|
||||||
sizeof(name).TSocklen) < 0'i32:
|
sizeof(name).TSockLen) < 0'i32:
|
||||||
osError(osLastError())
|
osError(osLastError())
|
||||||
else:
|
else:
|
||||||
var hints: Taddrinfo
|
var hints: TAddrInfo
|
||||||
var aiList: ptr Taddrinfo = nil
|
var aiList: ptr TAddrInfo = nil
|
||||||
hints.ai_family = toInt(AF_INET)
|
hints.ai_family = toInt(AF_INET)
|
||||||
hints.ai_socktype = toInt(SOCK_STREAM)
|
hints.ai_socktype = toInt(SOCK_STREAM)
|
||||||
hints.ai_protocol = toInt(IPPROTO_TCP)
|
hints.ai_protocol = toInt(IPPROTO_TCP)
|
||||||
gaiNim(address, port, hints, aiList)
|
gaiNim(address, port, hints, aiList)
|
||||||
if bindSocket(socket.fd, aiList.ai_addr, aiList.ai_addrlen.TSocklen) < 0'i32:
|
if bindSocket(socket.fd, aiList.ai_addr, aiList.ai_addrlen.TSockLen) < 0'i32:
|
||||||
osError(osLastError())
|
osError(osLastError())
|
||||||
|
|
||||||
proc getSockName*(socket: TSocket): TPort =
|
proc getSockName*(socket: TSocket): TPort =
|
||||||
|
|
@ -460,7 +460,7 @@ proc getSockName*(socket: TSocket): TPort =
|
||||||
name.sin_family = posix.AF_INET
|
name.sin_family = posix.AF_INET
|
||||||
#name.sin_port = htons(cint16(port))
|
#name.sin_port = htons(cint16(port))
|
||||||
#name.sin_addr.s_addr = htonl(INADDR_ANY)
|
#name.sin_addr.s_addr = htonl(INADDR_ANY)
|
||||||
var namelen = sizeof(name).TSocklen
|
var namelen = sizeof(name).TSockLen
|
||||||
if getsockname(socket.fd, cast[ptr TSockAddr](addr(name)),
|
if getsockname(socket.fd, cast[ptr TSockAddr](addr(name)),
|
||||||
addr(namelen)) == -1'i32:
|
addr(namelen)) == -1'i32:
|
||||||
osError(osLastError())
|
osError(osLastError())
|
||||||
|
|
@ -470,7 +470,7 @@ template acceptAddrPlain(noClientRet, successRet: expr,
|
||||||
sslImplementation: stmt): stmt {.immediate.} =
|
sslImplementation: stmt): stmt {.immediate.} =
|
||||||
assert(client != nil)
|
assert(client != nil)
|
||||||
var sockAddress: Tsockaddr_in
|
var sockAddress: Tsockaddr_in
|
||||||
var addrLen = sizeof(sockAddress).TSocklen
|
var addrLen = sizeof(sockAddress).TSockLen
|
||||||
var sock = accept(server.fd, cast[ptr TSockAddr](addr(sockAddress)),
|
var sock = accept(server.fd, cast[ptr TSockAddr](addr(sockAddress)),
|
||||||
addr(addrLen))
|
addr(addrLen))
|
||||||
|
|
||||||
|
|
@ -506,7 +506,7 @@ template acceptAddrPlain(noClientRet, successRet: expr,
|
||||||
return successRet
|
return successRet
|
||||||
|
|
||||||
proc acceptAddr*(server: TSocket, client: var TSocket, address: var string) {.
|
proc acceptAddr*(server: TSocket, client: var TSocket, address: var string) {.
|
||||||
tags: [FReadIO].} =
|
tags: [ReadIOEffect].} =
|
||||||
## Blocks until a connection is being made from a client. When a connection
|
## Blocks until a connection is being made from a client. When a connection
|
||||||
## is made sets ``client`` to the client socket and ``address`` to the address
|
## is made sets ``client`` to the client socket and ``address`` to the address
|
||||||
## of the connecting client.
|
## of the connecting client.
|
||||||
|
|
@ -601,7 +601,7 @@ when defined(ssl):
|
||||||
acceptAddrPlain(AcceptNoClient, AcceptSuccess):
|
acceptAddrPlain(AcceptNoClient, AcceptSuccess):
|
||||||
doHandshake()
|
doHandshake()
|
||||||
|
|
||||||
proc accept*(server: TSocket, client: var TSocket) {.tags: [FReadIO].} =
|
proc accept*(server: TSocket, client: var TSocket) {.tags: [ReadIOEffect].} =
|
||||||
## Equivalent to ``acceptAddr`` but doesn't return the address, only the
|
## Equivalent to ``acceptAddr`` but doesn't return the address, only the
|
||||||
## socket.
|
## socket.
|
||||||
##
|
##
|
||||||
|
|
@ -612,7 +612,7 @@ proc accept*(server: TSocket, client: var TSocket) {.tags: [FReadIO].} =
|
||||||
acceptAddr(server, client, addrDummy)
|
acceptAddr(server, client, addrDummy)
|
||||||
|
|
||||||
proc acceptAddr*(server: TSocket): tuple[client: TSocket, address: string] {.
|
proc acceptAddr*(server: TSocket): tuple[client: TSocket, address: string] {.
|
||||||
deprecated, tags: [FReadIO].} =
|
deprecated, tags: [ReadIOEffect].} =
|
||||||
## Slightly different version of ``acceptAddr``.
|
## Slightly different version of ``acceptAddr``.
|
||||||
##
|
##
|
||||||
## **Deprecated since version 0.9.0:** Please use the function above.
|
## **Deprecated since version 0.9.0:** Please use the function above.
|
||||||
|
|
@ -622,7 +622,7 @@ proc acceptAddr*(server: TSocket): tuple[client: TSocket, address: string] {.
|
||||||
acceptAddr(server, client, address)
|
acceptAddr(server, client, address)
|
||||||
return (client, address)
|
return (client, address)
|
||||||
|
|
||||||
proc accept*(server: TSocket): TSocket {.deprecated, tags: [FReadIO].} =
|
proc accept*(server: TSocket): TSocket {.deprecated, tags: [ReadIOEffect].} =
|
||||||
## **Deprecated since version 0.9.0:** Please use the function above.
|
## **Deprecated since version 0.9.0:** Please use the function above.
|
||||||
new(result)
|
new(result)
|
||||||
var address = ""
|
var address = ""
|
||||||
|
|
@ -640,7 +640,7 @@ proc close*(socket: TSocket) =
|
||||||
if socket.isSSL:
|
if socket.isSSL:
|
||||||
discard SSLShutdown(socket.sslHandle)
|
discard SSLShutdown(socket.sslHandle)
|
||||||
|
|
||||||
proc getServByName*(name, proto: string): TServent {.tags: [FReadIO].} =
|
proc getServByName*(name, proto: string): TServent {.tags: [ReadIOEffect].} =
|
||||||
## Searches the database from the beginning and finds the first entry for
|
## Searches the database from the beginning and finds the first entry for
|
||||||
## which the service name specified by ``name`` matches the s_name member
|
## which the service name specified by ``name`` matches the s_name member
|
||||||
## and the protocol name specified by ``proto`` matches the s_proto member.
|
## and the protocol name specified by ``proto`` matches the s_proto member.
|
||||||
|
|
@ -650,13 +650,13 @@ proc getServByName*(name, proto: string): TServent {.tags: [FReadIO].} =
|
||||||
var s = winlean.getservbyname(name, proto)
|
var s = winlean.getservbyname(name, proto)
|
||||||
else:
|
else:
|
||||||
var s = posix.getservbyname(name, proto)
|
var s = posix.getservbyname(name, proto)
|
||||||
if s == nil: raise newException(EOS, "Service not found.")
|
if s == nil: raise newException(OSError, "Service not found.")
|
||||||
result.name = $s.s_name
|
result.name = $s.s_name
|
||||||
result.aliases = cstringArrayToSeq(s.s_aliases)
|
result.aliases = cstringArrayToSeq(s.s_aliases)
|
||||||
result.port = TPort(s.s_port)
|
result.port = TPort(s.s_port)
|
||||||
result.proto = $s.s_proto
|
result.proto = $s.s_proto
|
||||||
|
|
||||||
proc getServByPort*(port: TPort, proto: string): TServent {.tags: [FReadIO].} =
|
proc getServByPort*(port: TPort, proto: string): TServent {.tags: [ReadIOEffect].} =
|
||||||
## Searches the database from the beginning and finds the first entry for
|
## Searches the database from the beginning and finds the first entry for
|
||||||
## which the port specified by ``port`` matches the s_port member and the
|
## which the port specified by ``port`` matches the s_port member and the
|
||||||
## protocol name specified by ``proto`` matches the s_proto member.
|
## protocol name specified by ``proto`` matches the s_proto member.
|
||||||
|
|
@ -666,13 +666,13 @@ proc getServByPort*(port: TPort, proto: string): TServent {.tags: [FReadIO].} =
|
||||||
var s = winlean.getservbyport(ze(int16(port)).cint, proto)
|
var s = winlean.getservbyport(ze(int16(port)).cint, proto)
|
||||||
else:
|
else:
|
||||||
var s = posix.getservbyport(ze(int16(port)).cint, proto)
|
var s = posix.getservbyport(ze(int16(port)).cint, proto)
|
||||||
if s == nil: raise newException(EOS, "Service not found.")
|
if s == nil: raise newException(OSError, "Service not found.")
|
||||||
result.name = $s.s_name
|
result.name = $s.s_name
|
||||||
result.aliases = cstringArrayToSeq(s.s_aliases)
|
result.aliases = cstringArrayToSeq(s.s_aliases)
|
||||||
result.port = TPort(s.s_port)
|
result.port = TPort(s.s_port)
|
||||||
result.proto = $s.s_proto
|
result.proto = $s.s_proto
|
||||||
|
|
||||||
proc getHostByAddr*(ip: string): Thostent {.tags: [FReadIO].} =
|
proc getHostByAddr*(ip: string): Thostent {.tags: [ReadIOEffect].} =
|
||||||
## This function will lookup the hostname of an IP Address.
|
## This function will lookup the hostname of an IP Address.
|
||||||
var myaddr: TInAddr
|
var myaddr: TInAddr
|
||||||
myaddr.s_addr = inet_addr(ip)
|
myaddr.s_addr = inet_addr(ip)
|
||||||
|
|
@ -701,7 +701,7 @@ proc getHostByAddr*(ip: string): Thostent {.tags: [FReadIO].} =
|
||||||
result.addrList = cstringArrayToSeq(s.h_addr_list)
|
result.addrList = cstringArrayToSeq(s.h_addr_list)
|
||||||
result.length = int(s.h_length)
|
result.length = int(s.h_length)
|
||||||
|
|
||||||
proc getHostByName*(name: string): Thostent {.tags: [FReadIO].} =
|
proc getHostByName*(name: string): Thostent {.tags: [ReadIOEffect].} =
|
||||||
## This function will lookup the IP address of a hostname.
|
## This function will lookup the IP address of a hostname.
|
||||||
when defined(Windows):
|
when defined(Windows):
|
||||||
var s = winlean.gethostbyname(name)
|
var s = winlean.gethostbyname(name)
|
||||||
|
|
@ -723,21 +723,21 @@ proc getHostByName*(name: string): Thostent {.tags: [FReadIO].} =
|
||||||
result.length = int(s.h_length)
|
result.length = int(s.h_length)
|
||||||
|
|
||||||
proc getSockOptInt*(socket: TSocket, level, optname: int): int {.
|
proc getSockOptInt*(socket: TSocket, level, optname: int): int {.
|
||||||
tags: [FReadIO].} =
|
tags: [ReadIOEffect].} =
|
||||||
## getsockopt for integer options.
|
## getsockopt for integer options.
|
||||||
var res: cint
|
var res: cint
|
||||||
var size = sizeof(res).TSocklen
|
var size = sizeof(res).TSockLen
|
||||||
if getsockopt(socket.fd, cint(level), cint(optname),
|
if getsockopt(socket.fd, cint(level), cint(optname),
|
||||||
addr(res), addr(size)) < 0'i32:
|
addr(res), addr(size)) < 0'i32:
|
||||||
osError(osLastError())
|
osError(osLastError())
|
||||||
result = int(res)
|
result = int(res)
|
||||||
|
|
||||||
proc setSockOptInt*(socket: TSocket, level, optname, optval: int) {.
|
proc setSockOptInt*(socket: TSocket, level, optname, optval: int) {.
|
||||||
tags: [FWriteIO].} =
|
tags: [WriteIOEffect].} =
|
||||||
## setsockopt for integer options.
|
## setsockopt for integer options.
|
||||||
var value = cint(optval)
|
var value = cint(optval)
|
||||||
if setsockopt(socket.fd, cint(level), cint(optname), addr(value),
|
if setsockopt(socket.fd, cint(level), cint(optname), addr(value),
|
||||||
sizeof(value).TSocklen) < 0'i32:
|
sizeof(value).TSockLen) < 0'i32:
|
||||||
osError(osLastError())
|
osError(osLastError())
|
||||||
|
|
||||||
proc toCInt(opt: TSOBool): cint =
|
proc toCInt(opt: TSOBool): cint =
|
||||||
|
|
@ -751,33 +751,33 @@ proc toCInt(opt: TSOBool): cint =
|
||||||
of OptReuseAddr: SO_REUSEADDR
|
of OptReuseAddr: SO_REUSEADDR
|
||||||
|
|
||||||
proc getSockOpt*(socket: TSocket, opt: TSOBool, level = SOL_SOCKET): bool {.
|
proc getSockOpt*(socket: TSocket, opt: TSOBool, level = SOL_SOCKET): bool {.
|
||||||
tags: [FReadIO].} =
|
tags: [ReadIOEffect].} =
|
||||||
## Retrieves option ``opt`` as a boolean value.
|
## Retrieves option ``opt`` as a boolean value.
|
||||||
var res: cint
|
var res: cint
|
||||||
var size = sizeof(res).TSocklen
|
var size = sizeof(res).TSockLen
|
||||||
if getsockopt(socket.fd, cint(level), toCInt(opt),
|
if getsockopt(socket.fd, cint(level), toCInt(opt),
|
||||||
addr(res), addr(size)) < 0'i32:
|
addr(res), addr(size)) < 0'i32:
|
||||||
osError(osLastError())
|
osError(osLastError())
|
||||||
result = res != 0
|
result = res != 0
|
||||||
|
|
||||||
proc setSockOpt*(socket: TSocket, opt: TSOBool, value: bool, level = SOL_SOCKET) {.
|
proc setSockOpt*(socket: TSocket, opt: TSOBool, value: bool, level = SOL_SOCKET) {.
|
||||||
tags: [FWriteIO].} =
|
tags: [WriteIOEffect].} =
|
||||||
## Sets option ``opt`` to a boolean value specified by ``value``.
|
## Sets option ``opt`` to a boolean value specified by ``value``.
|
||||||
var valuei = cint(if value: 1 else: 0)
|
var valuei = cint(if value: 1 else: 0)
|
||||||
if setsockopt(socket.fd, cint(level), toCInt(opt), addr(valuei),
|
if setsockopt(socket.fd, cint(level), toCInt(opt), addr(valuei),
|
||||||
sizeof(valuei).TSocklen) < 0'i32:
|
sizeof(valuei).TSockLen) < 0'i32:
|
||||||
osError(osLastError())
|
osError(osLastError())
|
||||||
|
|
||||||
proc connect*(socket: TSocket, address: string, port = TPort(0),
|
proc connect*(socket: TSocket, address: string, port = TPort(0),
|
||||||
af: TDomain = AF_INET) {.tags: [FReadIO].} =
|
af: TDomain = AF_INET) {.tags: [ReadIOEffect].} =
|
||||||
## Connects socket to ``address``:``port``. ``Address`` can be an IP address or a
|
## Connects socket to ``address``:``port``. ``Address`` can be an IP address or a
|
||||||
## host name. If ``address`` is a host name, this function will try each IP
|
## host name. If ``address`` is a host name, this function will try each IP
|
||||||
## of that host name. ``htons`` is already performed on ``port`` so you must
|
## of that host name. ``htons`` is already performed on ``port`` so you must
|
||||||
## not do it.
|
## not do it.
|
||||||
##
|
##
|
||||||
## If ``socket`` is an SSL socket a handshake will be automatically performed.
|
## If ``socket`` is an SSL socket a handshake will be automatically performed.
|
||||||
var hints: Taddrinfo
|
var hints: TAddrInfo
|
||||||
var aiList: ptr Taddrinfo = nil
|
var aiList: ptr TAddrInfo = nil
|
||||||
hints.ai_family = toInt(af)
|
hints.ai_family = toInt(af)
|
||||||
hints.ai_socktype = toInt(SOCK_STREAM)
|
hints.ai_socktype = toInt(SOCK_STREAM)
|
||||||
hints.ai_protocol = toInt(IPPROTO_TCP)
|
hints.ai_protocol = toInt(IPPROTO_TCP)
|
||||||
|
|
@ -787,7 +787,7 @@ proc connect*(socket: TSocket, address: string, port = TPort(0),
|
||||||
var lastError: TOSErrorCode
|
var lastError: TOSErrorCode
|
||||||
var it = aiList
|
var it = aiList
|
||||||
while it != nil:
|
while it != nil:
|
||||||
if connect(socket.fd, it.ai_addr, it.ai_addrlen.TSocklen) == 0'i32:
|
if connect(socket.fd, it.ai_addr, it.ai_addrlen.TSockLen) == 0'i32:
|
||||||
success = true
|
success = true
|
||||||
break
|
break
|
||||||
else: lastError = osLastError()
|
else: lastError = osLastError()
|
||||||
|
|
@ -830,7 +830,7 @@ proc connect*(socket: TSocket, address: string, port = TPort(0),
|
||||||
OSError()
|
OSError()
|
||||||
|
|
||||||
proc connectAsync*(socket: TSocket, name: string, port = TPort(0),
|
proc connectAsync*(socket: TSocket, name: string, port = TPort(0),
|
||||||
af: TDomain = AF_INET) {.tags: [FReadIO].} =
|
af: TDomain = AF_INET) {.tags: [ReadIOEffect].} =
|
||||||
## A variant of ``connect`` for non-blocking sockets.
|
## A variant of ``connect`` for non-blocking sockets.
|
||||||
##
|
##
|
||||||
## This procedure will immediatelly return, it will not block until a connection
|
## This procedure will immediatelly return, it will not block until a connection
|
||||||
|
|
@ -839,8 +839,8 @@ proc connectAsync*(socket: TSocket, name: string, port = TPort(0),
|
||||||
##
|
##
|
||||||
## **Note**: For SSL sockets, the ``handshake`` procedure must be called
|
## **Note**: For SSL sockets, the ``handshake`` procedure must be called
|
||||||
## whenever the socket successfully connects to a server.
|
## whenever the socket successfully connects to a server.
|
||||||
var hints: Taddrinfo
|
var hints: TAddrInfo
|
||||||
var aiList: ptr Taddrinfo = nil
|
var aiList: ptr TAddrInfo = nil
|
||||||
hints.ai_family = toInt(af)
|
hints.ai_family = toInt(af)
|
||||||
hints.ai_socktype = toInt(SOCK_STREAM)
|
hints.ai_socktype = toInt(SOCK_STREAM)
|
||||||
hints.ai_protocol = toInt(IPPROTO_TCP)
|
hints.ai_protocol = toInt(IPPROTO_TCP)
|
||||||
|
|
@ -850,7 +850,7 @@ proc connectAsync*(socket: TSocket, name: string, port = TPort(0),
|
||||||
var lastError: TOSErrorCode
|
var lastError: TOSErrorCode
|
||||||
var it = aiList
|
var it = aiList
|
||||||
while it != nil:
|
while it != nil:
|
||||||
var ret = connect(socket.fd, it.ai_addr, it.ai_addrlen.TSocklen)
|
var ret = connect(socket.fd, it.ai_addr, it.ai_addrlen.TSockLen)
|
||||||
if ret == 0'i32:
|
if ret == 0'i32:
|
||||||
success = true
|
success = true
|
||||||
break
|
break
|
||||||
|
|
@ -915,7 +915,7 @@ when defined(ssl):
|
||||||
else:
|
else:
|
||||||
SSLError("Socket is not an SSL socket.")
|
SSLError("Socket is not an SSL socket.")
|
||||||
|
|
||||||
proc timeValFromMilliseconds(timeout = 500): Ttimeval =
|
proc timeValFromMilliseconds(timeout = 500): TTimeval =
|
||||||
if timeout != -1:
|
if timeout != -1:
|
||||||
var seconds = timeout div 1000
|
var seconds = timeout div 1000
|
||||||
result.tv_sec = seconds.int32
|
result.tv_sec = seconds.int32
|
||||||
|
|
@ -962,7 +962,7 @@ proc checkBuffer(readfds: var seq[TSocket]): int =
|
||||||
readfds = res
|
readfds = res
|
||||||
|
|
||||||
proc select*(readfds, writefds, exceptfds: var seq[TSocket],
|
proc select*(readfds, writefds, exceptfds: var seq[TSocket],
|
||||||
timeout = 500): int {.tags: [FReadIO].} =
|
timeout = 500): int {.tags: [ReadIOEffect].} =
|
||||||
## Traditional select function. This function will return the number of
|
## Traditional select function. This function will return the number of
|
||||||
## sockets that are ready to be read from, written to, or which have errors.
|
## sockets that are ready to be read from, written to, or which have errors.
|
||||||
## If there are none; 0 is returned.
|
## If there are none; 0 is returned.
|
||||||
|
|
@ -975,7 +975,7 @@ proc select*(readfds, writefds, exceptfds: var seq[TSocket],
|
||||||
if buffersFilled > 0:
|
if buffersFilled > 0:
|
||||||
return buffersFilled
|
return buffersFilled
|
||||||
|
|
||||||
var tv {.noInit.}: Ttimeval = timeValFromMilliseconds(timeout)
|
var tv {.noInit.}: TTimeval = timeValFromMilliseconds(timeout)
|
||||||
|
|
||||||
var rd, wr, ex: TFdSet
|
var rd, wr, ex: TFdSet
|
||||||
var m = 0
|
var m = 0
|
||||||
|
|
@ -993,12 +993,12 @@ proc select*(readfds, writefds, exceptfds: var seq[TSocket],
|
||||||
pruneSocketSet(exceptfds, (ex))
|
pruneSocketSet(exceptfds, (ex))
|
||||||
|
|
||||||
proc select*(readfds, writefds: var seq[TSocket],
|
proc select*(readfds, writefds: var seq[TSocket],
|
||||||
timeout = 500): int {.tags: [FReadIO].} =
|
timeout = 500): int {.tags: [ReadIOEffect].} =
|
||||||
## Variant of select with only a read and write list.
|
## Variant of select with only a read and write list.
|
||||||
let buffersFilled = checkBuffer(readfds)
|
let buffersFilled = checkBuffer(readfds)
|
||||||
if buffersFilled > 0:
|
if buffersFilled > 0:
|
||||||
return buffersFilled
|
return buffersFilled
|
||||||
var tv {.noInit.}: Ttimeval = timeValFromMilliseconds(timeout)
|
var tv {.noInit.}: TTimeval = timeValFromMilliseconds(timeout)
|
||||||
|
|
||||||
var rd, wr: TFdSet
|
var rd, wr: TFdSet
|
||||||
var m = 0
|
var m = 0
|
||||||
|
|
@ -1014,7 +1014,7 @@ proc select*(readfds, writefds: var seq[TSocket],
|
||||||
pruneSocketSet(writefds, (wr))
|
pruneSocketSet(writefds, (wr))
|
||||||
|
|
||||||
proc selectWrite*(writefds: var seq[TSocket],
|
proc selectWrite*(writefds: var seq[TSocket],
|
||||||
timeout = 500): int {.tags: [FReadIO].} =
|
timeout = 500): int {.tags: [ReadIOEffect].} =
|
||||||
## When a socket in ``writefds`` is ready to be written to then a non-zero
|
## When a socket in ``writefds`` is ready to be written to then a non-zero
|
||||||
## value will be returned specifying the count of the sockets which can be
|
## value will be returned specifying the count of the sockets which can be
|
||||||
## written to. The sockets which **cannot** be written to will also be removed
|
## written to. The sockets which **cannot** be written to will also be removed
|
||||||
|
|
@ -1022,7 +1022,7 @@ proc selectWrite*(writefds: var seq[TSocket],
|
||||||
##
|
##
|
||||||
## ``timeout`` is specified in miliseconds and ``-1`` can be specified for
|
## ``timeout`` is specified in miliseconds and ``-1`` can be specified for
|
||||||
## an unlimited time.
|
## an unlimited time.
|
||||||
var tv {.noInit.}: Ttimeval = timeValFromMilliseconds(timeout)
|
var tv {.noInit.}: TTimeval = timeValFromMilliseconds(timeout)
|
||||||
|
|
||||||
var wr: TFdSet
|
var wr: TFdSet
|
||||||
var m = 0
|
var m = 0
|
||||||
|
|
@ -1040,7 +1040,7 @@ proc select*(readfds: var seq[TSocket], timeout = 500): int =
|
||||||
let buffersFilled = checkBuffer(readfds)
|
let buffersFilled = checkBuffer(readfds)
|
||||||
if buffersFilled > 0:
|
if buffersFilled > 0:
|
||||||
return buffersFilled
|
return buffersFilled
|
||||||
var tv {.noInit.}: Ttimeval = timeValFromMilliseconds(timeout)
|
var tv {.noInit.}: TTimeval = timeValFromMilliseconds(timeout)
|
||||||
|
|
||||||
var rd: TFdSet
|
var rd: TFdSet
|
||||||
var m = 0
|
var m = 0
|
||||||
|
|
@ -1077,7 +1077,7 @@ template retRead(flags, readBytes: int) {.dirty.} =
|
||||||
else:
|
else:
|
||||||
return res
|
return res
|
||||||
|
|
||||||
proc recv*(socket: TSocket, data: pointer, size: int): int {.tags: [FReadIO].} =
|
proc recv*(socket: TSocket, data: pointer, size: int): int {.tags: [ReadIOEffect].} =
|
||||||
## Receives data from a socket.
|
## Receives data from a socket.
|
||||||
##
|
##
|
||||||
## **Note**: This is a low-level function, you may be interested in the higher
|
## **Note**: This is a low-level function, you may be interested in the higher
|
||||||
|
|
@ -1118,7 +1118,7 @@ proc recv*(socket: TSocket, data: pointer, size: int): int {.tags: [FReadIO].} =
|
||||||
result = recv(socket.fd, data, size.cint, 0'i32)
|
result = recv(socket.fd, data, size.cint, 0'i32)
|
||||||
|
|
||||||
proc waitFor(socket: TSocket, waited: var float, timeout, size: int,
|
proc waitFor(socket: TSocket, waited: var float, timeout, size: int,
|
||||||
funcName: string): int {.tags: [FTime].} =
|
funcName: string): int {.tags: [TimeEffect].} =
|
||||||
## determines the amount of characters that can be read. Result will never
|
## determines the amount of characters that can be read. Result will never
|
||||||
## be larger than ``size``. For unbuffered sockets this will be ``1``.
|
## be larger than ``size``. For unbuffered sockets this will be ``1``.
|
||||||
## For buffered sockets it can be as big as ``BufferSize``.
|
## For buffered sockets it can be as big as ``BufferSize``.
|
||||||
|
|
@ -1153,7 +1153,7 @@ proc waitFor(socket: TSocket, waited: var float, timeout, size: int,
|
||||||
waited += (epochTime() - startTime)
|
waited += (epochTime() - startTime)
|
||||||
|
|
||||||
proc recv*(socket: TSocket, data: pointer, size: int, timeout: int): int {.
|
proc recv*(socket: TSocket, data: pointer, size: int, timeout: int): int {.
|
||||||
tags: [FReadIO, FTime].} =
|
tags: [ReadIOEffect, FTime].} =
|
||||||
## overload with a ``timeout`` parameter in miliseconds.
|
## overload with a ``timeout`` parameter in miliseconds.
|
||||||
var waited = 0.0 # number of seconds already waited
|
var waited = 0.0 # number of seconds already waited
|
||||||
|
|
||||||
|
|
@ -1203,7 +1203,7 @@ proc recvAsync*(socket: TSocket, data: var string, size: int): int =
|
||||||
result = -1
|
result = -1
|
||||||
data.setLen(result)
|
data.setLen(result)
|
||||||
|
|
||||||
proc peekChar(socket: TSocket, c: var char): int {.tags: [FReadIO].} =
|
proc peekChar(socket: TSocket, c: var char): int {.tags: [ReadIOEffect].} =
|
||||||
if socket.isBuffered:
|
if socket.isBuffered:
|
||||||
result = 1
|
result = 1
|
||||||
if socket.bufLen == 0 or socket.currPos > socket.bufLen-1:
|
if socket.bufLen == 0 or socket.currPos > socket.bufLen-1:
|
||||||
|
|
@ -1224,7 +1224,7 @@ proc peekChar(socket: TSocket, c: var char): int {.tags: [FReadIO].} =
|
||||||
result = recv(socket.fd, addr(c), 1, MSG_PEEK)
|
result = recv(socket.fd, addr(c), 1, MSG_PEEK)
|
||||||
|
|
||||||
proc recvLine*(socket: TSocket, line: var TaintedString, timeout = -1): bool {.
|
proc recvLine*(socket: TSocket, line: var TaintedString, timeout = -1): bool {.
|
||||||
tags: [FReadIO, FTime], deprecated.} =
|
tags: [ReadIOEffect, FTime], deprecated.} =
|
||||||
## Receive a line of data from ``socket``.
|
## Receive a line of data from ``socket``.
|
||||||
##
|
##
|
||||||
## If a full line is received ``\r\L`` is not
|
## If a full line is received ``\r\L`` is not
|
||||||
|
|
@ -1271,7 +1271,7 @@ proc recvLine*(socket: TSocket, line: var TaintedString, timeout = -1): bool {.
|
||||||
add(line.string, c)
|
add(line.string, c)
|
||||||
|
|
||||||
proc readLine*(socket: TSocket, line: var TaintedString, timeout = -1) {.
|
proc readLine*(socket: TSocket, line: var TaintedString, timeout = -1) {.
|
||||||
tags: [FReadIO, FTime].} =
|
tags: [ReadIOEffect, FTime].} =
|
||||||
## Reads a line of data from ``socket``.
|
## Reads a line of data from ``socket``.
|
||||||
##
|
##
|
||||||
## If a full line is read ``\r\L`` is not
|
## If a full line is read ``\r\L`` is not
|
||||||
|
|
@ -1312,7 +1312,7 @@ proc readLine*(socket: TSocket, line: var TaintedString, timeout = -1) {.
|
||||||
add(line.string, c)
|
add(line.string, c)
|
||||||
|
|
||||||
proc recvLineAsync*(socket: TSocket,
|
proc recvLineAsync*(socket: TSocket,
|
||||||
line: var TaintedString): TRecvLineResult {.tags: [FReadIO], deprecated.} =
|
line: var TaintedString): TRecvLineResult {.tags: [ReadIOEffect], deprecated.} =
|
||||||
## Similar to ``recvLine`` but designed for non-blocking sockets.
|
## Similar to ``recvLine`` but designed for non-blocking sockets.
|
||||||
##
|
##
|
||||||
## The values of the returned enum should be pretty self explanatory:
|
## The values of the returned enum should be pretty self explanatory:
|
||||||
|
|
@ -1344,7 +1344,7 @@ proc recvLineAsync*(socket: TSocket,
|
||||||
add(line.string, c)
|
add(line.string, c)
|
||||||
|
|
||||||
proc readLineAsync*(socket: TSocket,
|
proc readLineAsync*(socket: TSocket,
|
||||||
line: var TaintedString): TReadLineResult {.tags: [FReadIO].} =
|
line: var TaintedString): TReadLineResult {.tags: [ReadIOEffect].} =
|
||||||
## Similar to ``recvLine`` but designed for non-blocking sockets.
|
## Similar to ``recvLine`` but designed for non-blocking sockets.
|
||||||
##
|
##
|
||||||
## The values of the returned enum should be pretty self explanatory:
|
## The values of the returned enum should be pretty self explanatory:
|
||||||
|
|
@ -1378,7 +1378,7 @@ proc readLineAsync*(socket: TSocket,
|
||||||
elif c == '\L': return ReadFullLine
|
elif c == '\L': return ReadFullLine
|
||||||
add(line.string, c)
|
add(line.string, c)
|
||||||
|
|
||||||
proc recv*(socket: TSocket): TaintedString {.tags: [FReadIO], deprecated.} =
|
proc recv*(socket: TSocket): TaintedString {.tags: [ReadIOEffect], deprecated.} =
|
||||||
## receives all the available data from the socket.
|
## receives all the available data from the socket.
|
||||||
## Socket errors will result in an ``EOS`` error.
|
## Socket errors will result in an ``EOS`` error.
|
||||||
## If socket is not a connectionless socket and socket is not connected
|
## If socket is not a connectionless socket and socket is not connected
|
||||||
|
|
@ -1411,7 +1411,7 @@ proc recv*(socket: TSocket): TaintedString {.tags: [FReadIO], deprecated.} =
|
||||||
|
|
||||||
{.push warning[deprecated]: off.}
|
{.push warning[deprecated]: off.}
|
||||||
proc recvTimeout*(socket: TSocket, timeout: int): TaintedString {.
|
proc recvTimeout*(socket: TSocket, timeout: int): TaintedString {.
|
||||||
tags: [FReadIO], deprecated.} =
|
tags: [ReadIOEffect], deprecated.} =
|
||||||
## overloaded variant to support a ``timeout`` parameter, the ``timeout``
|
## overloaded variant to support a ``timeout`` parameter, the ``timeout``
|
||||||
## parameter specifies the amount of miliseconds to wait for data on the
|
## parameter specifies the amount of miliseconds to wait for data on the
|
||||||
## socket.
|
## socket.
|
||||||
|
|
@ -1426,7 +1426,7 @@ proc recvTimeout*(socket: TSocket, timeout: int): TaintedString {.
|
||||||
{.pop.}
|
{.pop.}
|
||||||
|
|
||||||
proc recvAsync*(socket: TSocket, s: var TaintedString): bool {.
|
proc recvAsync*(socket: TSocket, s: var TaintedString): bool {.
|
||||||
tags: [FReadIO], deprecated.} =
|
tags: [ReadIOEffect], deprecated.} =
|
||||||
## receives all the data from a non-blocking socket. If socket is non-blocking
|
## receives all the data from a non-blocking socket. If socket is non-blocking
|
||||||
## and there are no messages available, `False` will be returned.
|
## and there are no messages available, `False` will be returned.
|
||||||
## Other socket errors will result in an ``EOS`` error.
|
## Other socket errors will result in an ``EOS`` error.
|
||||||
|
|
@ -1478,7 +1478,7 @@ proc recvAsync*(socket: TSocket, s: var TaintedString): bool {.
|
||||||
|
|
||||||
proc recvFrom*(socket: TSocket, data: var string, length: int,
|
proc recvFrom*(socket: TSocket, data: var string, length: int,
|
||||||
address: var string, port: var TPort, flags = 0'i32): int {.
|
address: var string, port: var TPort, flags = 0'i32): int {.
|
||||||
tags: [FReadIO].} =
|
tags: [ReadIOEffect].} =
|
||||||
## Receives data from ``socket``. This function should normally be used with
|
## Receives data from ``socket``. This function should normally be used with
|
||||||
## connection-less sockets (UDP sockets).
|
## connection-less sockets (UDP sockets).
|
||||||
##
|
##
|
||||||
|
|
@ -1493,7 +1493,7 @@ proc recvFrom*(socket: TSocket, data: var string, length: int,
|
||||||
# TODO: Buffered sockets
|
# TODO: Buffered sockets
|
||||||
data.setLen(length)
|
data.setLen(length)
|
||||||
var sockAddress: Tsockaddr_in
|
var sockAddress: Tsockaddr_in
|
||||||
var addrLen = sizeof(sockAddress).TSocklen
|
var addrLen = sizeof(sockAddress).TSockLen
|
||||||
result = recvfrom(socket.fd, cstring(data), length.cint, flags.cint,
|
result = recvfrom(socket.fd, cstring(data), length.cint, flags.cint,
|
||||||
cast[ptr TSockAddr](addr(sockAddress)), addr(addrLen))
|
cast[ptr TSockAddr](addr(sockAddress)), addr(addrLen))
|
||||||
|
|
||||||
|
|
@ -1504,7 +1504,7 @@ proc recvFrom*(socket: TSocket, data: var string, length: int,
|
||||||
|
|
||||||
proc recvFromAsync*(socket: TSocket, data: var string, length: int,
|
proc recvFromAsync*(socket: TSocket, data: var string, length: int,
|
||||||
address: var string, port: var TPort,
|
address: var string, port: var TPort,
|
||||||
flags = 0'i32): bool {.tags: [FReadIO].} =
|
flags = 0'i32): bool {.tags: [ReadIOEffect].} =
|
||||||
## Variant of ``recvFrom`` for non-blocking sockets. Unlike ``recvFrom``,
|
## Variant of ``recvFrom`` for non-blocking sockets. Unlike ``recvFrom``,
|
||||||
## this function will raise an EOS error whenever a socket error occurs.
|
## this function will raise an EOS error whenever a socket error occurs.
|
||||||
##
|
##
|
||||||
|
|
@ -1522,7 +1522,7 @@ proc recvFromAsync*(socket: TSocket, data: var string, length: int,
|
||||||
return false
|
return false
|
||||||
else: osError(err)
|
else: osError(err)
|
||||||
|
|
||||||
proc skip*(socket: TSocket) {.tags: [FReadIO], deprecated.} =
|
proc skip*(socket: TSocket) {.tags: [ReadIOEffect], deprecated.} =
|
||||||
## skips all the data that is pending for the socket
|
## skips all the data that is pending for the socket
|
||||||
##
|
##
|
||||||
## **Deprecated since version 0.9.2**: This function is not safe for use.
|
## **Deprecated since version 0.9.2**: This function is not safe for use.
|
||||||
|
|
@ -1547,7 +1547,7 @@ proc skip*(socket: TSocket, size: int, timeout = -1) =
|
||||||
dealloc(dummy)
|
dealloc(dummy)
|
||||||
|
|
||||||
proc send*(socket: TSocket, data: pointer, size: int): int {.
|
proc send*(socket: TSocket, data: pointer, size: int): int {.
|
||||||
tags: [FWriteIO].} =
|
tags: [WriteIOEffect].} =
|
||||||
## sends data to a socket.
|
## sends data to a socket.
|
||||||
when defined(ssl):
|
when defined(ssl):
|
||||||
if socket.isSSL:
|
if socket.isSSL:
|
||||||
|
|
@ -1560,10 +1560,10 @@ proc send*(socket: TSocket, data: pointer, size: int): int {.
|
||||||
const MSG_NOSIGNAL = 0
|
const MSG_NOSIGNAL = 0
|
||||||
result = send(socket.fd, data, size, int32(MSG_NOSIGNAL))
|
result = send(socket.fd, data, size, int32(MSG_NOSIGNAL))
|
||||||
|
|
||||||
proc send*(socket: TSocket, data: string) {.tags: [FWriteIO].} =
|
proc send*(socket: TSocket, data: string) {.tags: [WriteIOEffect].} =
|
||||||
## sends data to a socket.
|
## sends data to a socket.
|
||||||
if socket.nonblocking:
|
if socket.nonblocking:
|
||||||
raise newException(EInvalidValue, "This function cannot be used on non-blocking sockets.")
|
raise newException(ValueError, "This function cannot be used on non-blocking sockets.")
|
||||||
let sent = send(socket, cstring(data), data.len)
|
let sent = send(socket, cstring(data), data.len)
|
||||||
if sent < 0:
|
if sent < 0:
|
||||||
when defined(ssl):
|
when defined(ssl):
|
||||||
|
|
@ -1573,9 +1573,9 @@ proc send*(socket: TSocket, data: string) {.tags: [FWriteIO].} =
|
||||||
osError(osLastError())
|
osError(osLastError())
|
||||||
|
|
||||||
if sent != data.len:
|
if sent != data.len:
|
||||||
raise newException(EOS, "Could not send all data.")
|
raise newException(OSError, "Could not send all data.")
|
||||||
|
|
||||||
proc sendAsync*(socket: TSocket, data: string): int {.tags: [FWriteIO].} =
|
proc sendAsync*(socket: TSocket, data: string): int {.tags: [WriteIOEffect].} =
|
||||||
## sends data to a non-blocking socket.
|
## sends data to a non-blocking socket.
|
||||||
## Returns ``0`` if no data could be sent, if data has been sent
|
## Returns ``0`` if no data could be sent, if data has been sent
|
||||||
## returns the amount of bytes of ``data`` that was successfully sent. This
|
## returns the amount of bytes of ``data`` that was successfully sent. This
|
||||||
|
|
@ -1614,21 +1614,21 @@ proc sendAsync*(socket: TSocket, data: string): int {.tags: [FWriteIO].} =
|
||||||
else: osError(err)
|
else: osError(err)
|
||||||
|
|
||||||
|
|
||||||
proc trySend*(socket: TSocket, data: string): bool {.tags: [FWriteIO].} =
|
proc trySend*(socket: TSocket, data: string): bool {.tags: [WriteIOEffect].} =
|
||||||
## safe alternative to ``send``. Does not raise an EOS when an error occurs,
|
## safe alternative to ``send``. Does not raise an EOS when an error occurs,
|
||||||
## and instead returns ``false`` on failure.
|
## and instead returns ``false`` on failure.
|
||||||
result = send(socket, cstring(data), data.len) == data.len
|
result = send(socket, cstring(data), data.len) == data.len
|
||||||
|
|
||||||
proc sendTo*(socket: TSocket, address: string, port: TPort, data: pointer,
|
proc sendTo*(socket: TSocket, address: string, port: TPort, data: pointer,
|
||||||
size: int, af: TDomain = AF_INET, flags = 0'i32): int {.
|
size: int, af: TDomain = AF_INET, flags = 0'i32): int {.
|
||||||
tags: [FWriteIO].} =
|
tags: [WriteIOEffect].} =
|
||||||
## low-level sendTo proc. This proc sends ``data`` to the specified ``address``,
|
## low-level sendTo proc. This proc sends ``data`` to the specified ``address``,
|
||||||
## which may be an IP address or a hostname, if a hostname is specified
|
## which may be an IP address or a hostname, if a hostname is specified
|
||||||
## this function will try each IP of that hostname.
|
## this function will try each IP of that hostname.
|
||||||
##
|
##
|
||||||
## **Note:** This proc is not available for SSL sockets.
|
## **Note:** This proc is not available for SSL sockets.
|
||||||
var hints: Taddrinfo
|
var hints: TAddrInfo
|
||||||
var aiList: ptr Taddrinfo = nil
|
var aiList: ptr TAddrInfo = nil
|
||||||
hints.ai_family = toInt(af)
|
hints.ai_family = toInt(af)
|
||||||
hints.ai_socktype = toInt(SOCK_STREAM)
|
hints.ai_socktype = toInt(SOCK_STREAM)
|
||||||
hints.ai_protocol = toInt(IPPROTO_TCP)
|
hints.ai_protocol = toInt(IPPROTO_TCP)
|
||||||
|
|
@ -1639,7 +1639,7 @@ proc sendTo*(socket: TSocket, address: string, port: TPort, data: pointer,
|
||||||
var it = aiList
|
var it = aiList
|
||||||
while it != nil:
|
while it != nil:
|
||||||
result = sendto(socket.fd, data, size.cint, flags.cint, it.ai_addr,
|
result = sendto(socket.fd, data, size.cint, flags.cint, it.ai_addr,
|
||||||
it.ai_addrlen.TSocklen)
|
it.ai_addrlen.TSockLen)
|
||||||
if result != -1'i32:
|
if result != -1'i32:
|
||||||
success = true
|
success = true
|
||||||
break
|
break
|
||||||
|
|
@ -1648,7 +1648,7 @@ proc sendTo*(socket: TSocket, address: string, port: TPort, data: pointer,
|
||||||
freeaddrinfo(aiList)
|
freeaddrinfo(aiList)
|
||||||
|
|
||||||
proc sendTo*(socket: TSocket, address: string, port: TPort,
|
proc sendTo*(socket: TSocket, address: string, port: TPort,
|
||||||
data: string): int {.tags: [FWriteIO].} =
|
data: string): int {.tags: [WriteIOEffect].} =
|
||||||
## Friendlier version of the low-level ``sendTo``.
|
## Friendlier version of the low-level ``sendTo``.
|
||||||
result = socket.sendTo(address, port, cstring(data), data.len)
|
result = socket.sendTo(address, port, cstring(data), data.len)
|
||||||
|
|
||||||
|
|
@ -1685,7 +1685,7 @@ discard """ proc setReuseAddr*(s: TSocket) =
|
||||||
OSError(OSLastError()) """
|
OSError(OSLastError()) """
|
||||||
|
|
||||||
proc connect*(socket: TSocket, address: string, port = TPort(0), timeout: int,
|
proc connect*(socket: TSocket, address: string, port = TPort(0), timeout: int,
|
||||||
af: TDomain = AF_INET) {.tags: [FReadIO, FWriteIO].} =
|
af: TDomain = AF_INET) {.tags: [ReadIOEffect, FWriteIO].} =
|
||||||
## Connects to server as specified by ``address`` on port specified by ``port``.
|
## Connects to server as specified by ``address`` on port specified by ``port``.
|
||||||
##
|
##
|
||||||
## The ``timeout`` paremeter specifies the time in miliseconds to allow for
|
## The ``timeout`` paremeter specifies the time in miliseconds to allow for
|
||||||
|
|
|
||||||
|
|
@ -14,13 +14,13 @@
|
||||||
|
|
||||||
include "system/inclrtl"
|
include "system/inclrtl"
|
||||||
|
|
||||||
proc newEIO(msg: string): ref EIO =
|
proc newEIO(msg: string): ref IOError =
|
||||||
new(result)
|
new(result)
|
||||||
result.msg = msg
|
result.msg = msg
|
||||||
|
|
||||||
type
|
type
|
||||||
PStream* = ref TStream
|
PStream* = ref TStream
|
||||||
TStream* = object of TObject ## Stream interface that supports
|
TStream* = object of RootObj ## Stream interface that supports
|
||||||
## writing or reading. Note that these fields
|
## writing or reading. Note that these fields
|
||||||
## here shouldn't be used directly. They are
|
## here shouldn't be used directly. They are
|
||||||
## accessible so that a stream implementation
|
## accessible so that a stream implementation
|
||||||
|
|
@ -30,10 +30,10 @@ type
|
||||||
setPositionImpl*: proc (s: PStream, pos: int) {.nimcall, tags: [], gcsafe.}
|
setPositionImpl*: proc (s: PStream, pos: int) {.nimcall, tags: [], gcsafe.}
|
||||||
getPositionImpl*: proc (s: PStream): int {.nimcall, tags: [], gcsafe.}
|
getPositionImpl*: proc (s: PStream): int {.nimcall, tags: [], gcsafe.}
|
||||||
readDataImpl*: proc (s: PStream, buffer: pointer,
|
readDataImpl*: proc (s: PStream, buffer: pointer,
|
||||||
bufLen: int): int {.nimcall, tags: [FReadIO], gcsafe.}
|
bufLen: int): int {.nimcall, tags: [ReadIOEffect], gcsafe.}
|
||||||
writeDataImpl*: proc (s: PStream, buffer: pointer, bufLen: int) {.nimcall,
|
writeDataImpl*: proc (s: PStream, buffer: pointer, bufLen: int) {.nimcall,
|
||||||
tags: [FWriteIO], gcsafe.}
|
tags: [WriteIOEffect], gcsafe.}
|
||||||
flushImpl*: proc (s: PStream) {.nimcall, tags: [FWriteIO], gcsafe.}
|
flushImpl*: proc (s: PStream) {.nimcall, tags: [WriteIOEffect], gcsafe.}
|
||||||
|
|
||||||
proc flush*(s: PStream) =
|
proc flush*(s: PStream) =
|
||||||
## flushes the buffers that the stream `s` might use.
|
## flushes the buffers that the stream `s` might use.
|
||||||
|
|
@ -246,7 +246,7 @@ when not defined(js):
|
||||||
type
|
type
|
||||||
PFileStream* = ref TFileStream ## a stream that encapsulates a `TFile`
|
PFileStream* = ref TFileStream ## a stream that encapsulates a `TFile`
|
||||||
TFileStream* = object of TStream
|
TFileStream* = object of TStream
|
||||||
f: TFile
|
f: File
|
||||||
|
|
||||||
proc fsClose(s: PStream) =
|
proc fsClose(s: PStream) =
|
||||||
if PFileStream(s).f != nil:
|
if PFileStream(s).f != nil:
|
||||||
|
|
@ -264,7 +264,7 @@ when not defined(js):
|
||||||
if writeBuffer(PFileStream(s).f, buffer, bufLen) != bufLen:
|
if writeBuffer(PFileStream(s).f, buffer, bufLen) != bufLen:
|
||||||
raise newEIO("cannot write to stream")
|
raise newEIO("cannot write to stream")
|
||||||
|
|
||||||
proc newFileStream*(f: TFile): PFileStream =
|
proc newFileStream*(f: File): PFileStream =
|
||||||
## creates a new stream from the file `f`.
|
## creates a new stream from the file `f`.
|
||||||
new(result)
|
new(result)
|
||||||
result.f = f
|
result.f = f
|
||||||
|
|
@ -276,11 +276,11 @@ when not defined(js):
|
||||||
result.writeDataImpl = fsWriteData
|
result.writeDataImpl = fsWriteData
|
||||||
result.flushImpl = fsFlush
|
result.flushImpl = fsFlush
|
||||||
|
|
||||||
proc newFileStream*(filename: string, mode: TFileMode): PFileStream =
|
proc newFileStream*(filename: string, mode: FileMode): PFileStream =
|
||||||
## creates a new stream from the file named `filename` with the mode `mode`.
|
## creates a new stream from the file named `filename` with the mode `mode`.
|
||||||
## If the file cannot be opened, nil is returned. See the `system
|
## If the file cannot be opened, nil is returned. See the `system
|
||||||
## <system.html>`_ module for a list of available TFileMode enums.
|
## <system.html>`_ module for a list of available TFileMode enums.
|
||||||
var f: TFile
|
var f: File
|
||||||
if open(f, filename, mode): result = newFileStream(f)
|
if open(f, filename, mode): result = newFileStream(f)
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -24,7 +24,7 @@ type
|
||||||
modeStyleInsensitive ## the table is style insensitive
|
modeStyleInsensitive ## the table is style insensitive
|
||||||
TKeyValuePair = tuple[key, val: string]
|
TKeyValuePair = tuple[key, val: string]
|
||||||
TKeyValuePairSeq = seq[TKeyValuePair]
|
TKeyValuePairSeq = seq[TKeyValuePair]
|
||||||
TStringTable* = object of TObject
|
TStringTable* = object of RootObj
|
||||||
counter: int
|
counter: int
|
||||||
data: TKeyValuePairSeq
|
data: TKeyValuePairSeq
|
||||||
mode: TStringTableMode
|
mode: TStringTableMode
|
||||||
|
|
@ -110,7 +110,7 @@ proc mget*(t: PStringTable, key: string): var string {.
|
||||||
## ``EInvalidKey`` exception is raised.
|
## ``EInvalidKey`` exception is raised.
|
||||||
var index = rawGet(t, key)
|
var index = rawGet(t, key)
|
||||||
if index >= 0: result = t.data[index].val
|
if index >= 0: result = t.data[index].val
|
||||||
else: raise newException(EInvalidKey, "key does not exist: " & key)
|
else: raise newException(KeyError, "key does not exist: " & key)
|
||||||
|
|
||||||
proc hasKey*(t: PStringTable, key: string): bool {.rtl, extern: "nst$1".} =
|
proc hasKey*(t: PStringTable, key: string): bool {.rtl, extern: "nst$1".} =
|
||||||
## returns true iff `key` is in the table `t`.
|
## returns true iff `key` is in the table `t`.
|
||||||
|
|
@ -141,7 +141,7 @@ proc `[]=`*(t: PStringTable, key, val: string) {.rtl, extern: "nstPut".} =
|
||||||
inc(t.counter)
|
inc(t.counter)
|
||||||
|
|
||||||
proc raiseFormatException(s: string) =
|
proc raiseFormatException(s: string) =
|
||||||
var e: ref EInvalidValue
|
var e: ref ValueError
|
||||||
new(e)
|
new(e)
|
||||||
e.msg = "format string: key not found: " & s
|
e.msg = "format string: key not found: " & s
|
||||||
raise e
|
raise e
|
||||||
|
|
|
||||||
|
|
@ -420,7 +420,7 @@ proc parseInt*(s: string): int {.noSideEffect, procvar,
|
||||||
## If `s` is not a valid integer, `EInvalidValue` is raised.
|
## If `s` is not a valid integer, `EInvalidValue` is raised.
|
||||||
var L = parseutils.parseInt(s, result, 0)
|
var L = parseutils.parseInt(s, result, 0)
|
||||||
if L != s.len or L == 0:
|
if L != s.len or L == 0:
|
||||||
raise newException(EInvalidValue, "invalid integer: " & s)
|
raise newException(ValueError, "invalid integer: " & s)
|
||||||
|
|
||||||
proc parseBiggestInt*(s: string): BiggestInt {.noSideEffect, procvar,
|
proc parseBiggestInt*(s: string): BiggestInt {.noSideEffect, procvar,
|
||||||
rtl, extern: "nsuParseBiggestInt".} =
|
rtl, extern: "nsuParseBiggestInt".} =
|
||||||
|
|
@ -429,7 +429,7 @@ proc parseBiggestInt*(s: string): BiggestInt {.noSideEffect, procvar,
|
||||||
## If `s` is not a valid integer, `EInvalidValue` is raised.
|
## If `s` is not a valid integer, `EInvalidValue` is raised.
|
||||||
var L = parseutils.parseBiggestInt(s, result, 0)
|
var L = parseutils.parseBiggestInt(s, result, 0)
|
||||||
if L != s.len or L == 0:
|
if L != s.len or L == 0:
|
||||||
raise newException(EInvalidValue, "invalid integer: " & s)
|
raise newException(ValueError, "invalid integer: " & s)
|
||||||
|
|
||||||
proc parseFloat*(s: string): float {.noSideEffect, procvar,
|
proc parseFloat*(s: string): float {.noSideEffect, procvar,
|
||||||
rtl, extern: "nsuParseFloat".} =
|
rtl, extern: "nsuParseFloat".} =
|
||||||
|
|
@ -438,7 +438,7 @@ proc parseFloat*(s: string): float {.noSideEffect, procvar,
|
||||||
## ``INF``, ``-INF`` are also supported (case insensitive comparison).
|
## ``INF``, ``-INF`` are also supported (case insensitive comparison).
|
||||||
var L = parseutils.parseFloat(s, result, 0)
|
var L = parseutils.parseFloat(s, result, 0)
|
||||||
if L != s.len or L == 0:
|
if L != s.len or L == 0:
|
||||||
raise newException(EInvalidValue, "invalid float: " & s)
|
raise newException(ValueError, "invalid float: " & s)
|
||||||
|
|
||||||
proc parseHexInt*(s: string): int {.noSideEffect, procvar,
|
proc parseHexInt*(s: string): int {.noSideEffect, procvar,
|
||||||
rtl, extern: "nsuParseHexInt".} =
|
rtl, extern: "nsuParseHexInt".} =
|
||||||
|
|
@ -463,7 +463,7 @@ proc parseHexInt*(s: string): int {.noSideEffect, procvar,
|
||||||
result = result shl 4 or (ord(s[i]) - ord('A') + 10)
|
result = result shl 4 or (ord(s[i]) - ord('A') + 10)
|
||||||
inc(i)
|
inc(i)
|
||||||
of '\0': break
|
of '\0': break
|
||||||
else: raise newException(EInvalidValue, "invalid integer: " & s)
|
else: raise newException(ValueError, "invalid integer: " & s)
|
||||||
|
|
||||||
proc parseBool*(s: string): bool =
|
proc parseBool*(s: string): bool =
|
||||||
## Parses a value into a `bool`.
|
## Parses a value into a `bool`.
|
||||||
|
|
@ -475,7 +475,7 @@ proc parseBool*(s: string): bool =
|
||||||
case normalize(s)
|
case normalize(s)
|
||||||
of "y", "yes", "true", "1", "on": result = true
|
of "y", "yes", "true", "1", "on": result = true
|
||||||
of "n", "no", "false", "0", "off": result = false
|
of "n", "no", "false", "0", "off": result = false
|
||||||
else: raise newException(EInvalidValue, "cannot interpret as a bool: " & s)
|
else: raise newException(ValueError, "cannot interpret as a bool: " & s)
|
||||||
|
|
||||||
proc parseEnum*[T: enum](s: string): T =
|
proc parseEnum*[T: enum](s: string): T =
|
||||||
## Parses an enum ``T``.
|
## Parses an enum ``T``.
|
||||||
|
|
@ -485,7 +485,7 @@ proc parseEnum*[T: enum](s: string): T =
|
||||||
for e in low(T)..high(T):
|
for e in low(T)..high(T):
|
||||||
if cmpIgnoreStyle(s, $e) == 0:
|
if cmpIgnoreStyle(s, $e) == 0:
|
||||||
return e
|
return e
|
||||||
raise newException(EInvalidValue, "invalid enum value: " & s)
|
raise newException(ValueError, "invalid enum value: " & s)
|
||||||
|
|
||||||
proc parseEnum*[T: enum](s: string, default: T): T =
|
proc parseEnum*[T: enum](s: string, default: T): T =
|
||||||
## Parses an enum ``T``.
|
## Parses an enum ``T``.
|
||||||
|
|
@ -911,7 +911,7 @@ proc parseOctInt*(s: string): int {.noSideEffect,
|
||||||
result = result shl 3 or (ord(s[i]) - ord('0'))
|
result = result shl 3 or (ord(s[i]) - ord('0'))
|
||||||
inc(i)
|
inc(i)
|
||||||
of '\0': break
|
of '\0': break
|
||||||
else: raise newException(EInvalidValue, "invalid integer: " & s)
|
else: raise newException(ValueError, "invalid integer: " & s)
|
||||||
|
|
||||||
proc toOct*(x: BiggestInt, len: int): string {.noSideEffect,
|
proc toOct*(x: BiggestInt, len: int): string {.noSideEffect,
|
||||||
rtl, extern: "nsuToOct".} =
|
rtl, extern: "nsuToOct".} =
|
||||||
|
|
@ -1003,7 +1003,7 @@ proc unescape*(s: string, prefix = "\"", suffix = "\""): string {.noSideEffect,
|
||||||
result = newStringOfCap(s.len)
|
result = newStringOfCap(s.len)
|
||||||
var i = 0
|
var i = 0
|
||||||
if s[0 .. prefix.len-1] != prefix:
|
if s[0 .. prefix.len-1] != prefix:
|
||||||
raise newException(EInvalidValue,
|
raise newException(ValueError,
|
||||||
"String does not start with a prefix of: " & prefix)
|
"String does not start with a prefix of: " & prefix)
|
||||||
i.inc()
|
i.inc()
|
||||||
while true:
|
while true:
|
||||||
|
|
@ -1028,7 +1028,7 @@ proc unescape*(s: string, prefix = "\"", suffix = "\""): string {.noSideEffect,
|
||||||
result.add(s[i])
|
result.add(s[i])
|
||||||
i.inc()
|
i.inc()
|
||||||
if s[i .. -1] != suffix:
|
if s[i .. -1] != suffix:
|
||||||
raise newException(EInvalidValue,
|
raise newException(ValueError,
|
||||||
"String does not end with a suffix of: " & suffix)
|
"String does not end with a suffix of: " & suffix)
|
||||||
|
|
||||||
proc validIdentifier*(s: string): bool {.noSideEffect,
|
proc validIdentifier*(s: string): bool {.noSideEffect,
|
||||||
|
|
@ -1219,7 +1219,7 @@ proc findNormalized(x: string, inArray: openArray[string]): int =
|
||||||
return -1
|
return -1
|
||||||
|
|
||||||
proc invalidFormatString() {.noinline.} =
|
proc invalidFormatString() {.noinline.} =
|
||||||
raise newException(EInvalidValue, "invalid format string")
|
raise newException(ValueError, "invalid format string")
|
||||||
|
|
||||||
proc addf*(s: var string, formatstr: string, a: varargs[string, `$`]) {.
|
proc addf*(s: var string, formatstr: string, a: varargs[string, `$`]) {.
|
||||||
noSideEffect, rtl, extern: "nsuAddf".} =
|
noSideEffect, rtl, extern: "nsuAddf".} =
|
||||||
|
|
|
||||||
|
|
@ -103,7 +103,7 @@ elif defined(JS):
|
||||||
toLocaleString: proc (): cstring {.tags: [], raises: [], gcsafe.}
|
toLocaleString: proc (): cstring {.tags: [], raises: [], gcsafe.}
|
||||||
|
|
||||||
type
|
type
|
||||||
TTimeInfo* = object of TObject ## represents a time in different parts
|
TTimeInfo* = object of RootObj ## represents a time in different parts
|
||||||
second*: range[0..61] ## The number of seconds after the minute,
|
second*: range[0..61] ## The number of seconds after the minute,
|
||||||
## normally in the range 0 to 59, but can
|
## normally in the range 0 to 59, but can
|
||||||
## be up to 61 to allow for leap seconds.
|
## be up to 61 to allow for leap seconds.
|
||||||
|
|
@ -136,14 +136,14 @@ type
|
||||||
months*: int ## The number of months
|
months*: int ## The number of months
|
||||||
years*: int ## The number of years
|
years*: int ## The number of years
|
||||||
|
|
||||||
proc getTime*(): TTime {.tags: [FTime], gcsafe.}
|
proc getTime*(): TTime {.tags: [TimeEffect], gcsafe.}
|
||||||
## gets the current calendar time as a UNIX epoch value (number of seconds
|
## gets the current calendar time as a UNIX epoch value (number of seconds
|
||||||
## elapsed since 1970) with integer precission. Use epochTime for higher
|
## elapsed since 1970) with integer precission. Use epochTime for higher
|
||||||
## resolution.
|
## resolution.
|
||||||
proc getLocalTime*(t: TTime): TTimeInfo {.tags: [FTime], raises: [], gcsafe.}
|
proc getLocalTime*(t: TTime): TTimeInfo {.tags: [TimeEffect], raises: [], gcsafe.}
|
||||||
## converts the calendar time `t` to broken-time representation,
|
## converts the calendar time `t` to broken-time representation,
|
||||||
## expressed relative to the user's specified time zone.
|
## expressed relative to the user's specified time zone.
|
||||||
proc getGMTime*(t: TTime): TTimeInfo {.tags: [FTime], raises: [], gcsafe.}
|
proc getGMTime*(t: TTime): TTimeInfo {.tags: [TimeEffect], raises: [], gcsafe.}
|
||||||
## converts the calendar time `t` to broken-down time representation,
|
## converts the calendar time `t` to broken-down time representation,
|
||||||
## expressed in Coordinated Universal Time (UTC).
|
## expressed in Coordinated Universal Time (UTC).
|
||||||
|
|
||||||
|
|
@ -190,15 +190,15 @@ proc `==`*(a, b: TTime): bool {.
|
||||||
result = a - b == 0
|
result = a - b == 0
|
||||||
|
|
||||||
when not defined(JS):
|
when not defined(JS):
|
||||||
proc getTzname*(): tuple[nonDST, DST: string] {.tags: [FTime], raises: [],
|
proc getTzname*(): tuple[nonDST, DST: string] {.tags: [TimeEffect], raises: [],
|
||||||
gcsafe.}
|
gcsafe.}
|
||||||
## returns the local timezone; ``nonDST`` is the name of the local non-DST
|
## returns the local timezone; ``nonDST`` is the name of the local non-DST
|
||||||
## timezone, ``DST`` is the name of the local DST timezone.
|
## timezone, ``DST`` is the name of the local DST timezone.
|
||||||
|
|
||||||
proc getTimezone*(): int {.tags: [FTime], raises: [], gcsafe.}
|
proc getTimezone*(): int {.tags: [TimeEffect], raises: [], gcsafe.}
|
||||||
## returns the offset of the local (non-DST) timezone in seconds west of UTC.
|
## returns the offset of the local (non-DST) timezone in seconds west of UTC.
|
||||||
|
|
||||||
proc getStartMilsecs*(): int {.deprecated, tags: [FTime], gcsafe.}
|
proc getStartMilsecs*(): int {.deprecated, tags: [TimeEffect], gcsafe.}
|
||||||
## get the miliseconds from the start of the program. **Deprecated since
|
## get the miliseconds from the start of the program. **Deprecated since
|
||||||
## version 0.8.10.** Use ``epochTime`` or ``cpuTime`` instead.
|
## version 0.8.10.** Use ``epochTime`` or ``cpuTime`` instead.
|
||||||
|
|
||||||
|
|
@ -282,12 +282,12 @@ proc `-`*(a: TTimeInfo, interval: TTimeInterval): TTimeInfo =
|
||||||
result = getLocalTime(fromSeconds(t - secs))
|
result = getLocalTime(fromSeconds(t - secs))
|
||||||
|
|
||||||
when not defined(JS):
|
when not defined(JS):
|
||||||
proc epochTime*(): float {.rtl, extern: "nt$1", tags: [FTime].}
|
proc epochTime*(): float {.rtl, extern: "nt$1", tags: [TimeEffect].}
|
||||||
## gets time after the UNIX epoch (1970) in seconds. It is a float
|
## gets time after the UNIX epoch (1970) in seconds. It is a float
|
||||||
## because sub-second resolution is likely to be supported (depending
|
## because sub-second resolution is likely to be supported (depending
|
||||||
## on the hardware/OS).
|
## on the hardware/OS).
|
||||||
|
|
||||||
proc cpuTime*(): float {.rtl, extern: "nt$1", tags: [FTime].}
|
proc cpuTime*(): float {.rtl, extern: "nt$1", tags: [TimeEffect].}
|
||||||
## gets time spent that the CPU spent to run the current process in
|
## gets time spent that the CPU spent to run the current process in
|
||||||
## seconds. This may be more useful for benchmarking than ``epochTime``.
|
## seconds. This may be more useful for benchmarking than ``epochTime``.
|
||||||
## However, it may measure the real time instead (depending on the OS).
|
## However, it may measure the real time instead (depending on the OS).
|
||||||
|
|
@ -333,7 +333,7 @@ when not defined(JS):
|
||||||
importc: "ctime", header: "<time.h>", tags: [].}
|
importc: "ctime", header: "<time.h>", tags: [].}
|
||||||
# strftime(s: CString, maxsize: int, fmt: CString, t: tm): int {.
|
# strftime(s: CString, maxsize: int, fmt: CString, t: tm): int {.
|
||||||
# importc: "strftime", header: "<time.h>".}
|
# importc: "strftime", header: "<time.h>".}
|
||||||
proc clock(): TClock {.importc: "clock", header: "<time.h>", tags: [FTime].}
|
proc clock(): TClock {.importc: "clock", header: "<time.h>", tags: [TimeEffect].}
|
||||||
proc difftime(a, b: TTime): float {.importc: "difftime", header: "<time.h>",
|
proc difftime(a, b: TTime): float {.importc: "difftime", header: "<time.h>",
|
||||||
tags: [].}
|
tags: [].}
|
||||||
|
|
||||||
|
|
@ -458,7 +458,7 @@ when not defined(JS):
|
||||||
posix_gettimeofday(a)
|
posix_gettimeofday(a)
|
||||||
result = toFloat(a.tv_sec) + toFloat(a.tv_usec)*0.00_0001
|
result = toFloat(a.tv_sec) + toFloat(a.tv_usec)*0.00_0001
|
||||||
elif defined(windows):
|
elif defined(windows):
|
||||||
var f: winlean.TFiletime
|
var f: winlean.TFILETIME
|
||||||
getSystemTimeAsFileTime(f)
|
getSystemTimeAsFileTime(f)
|
||||||
var i64 = rdFileTime(f) - epochDiff
|
var i64 = rdFileTime(f) - epochDiff
|
||||||
var secs = i64 div rateDiff
|
var secs = i64 div rateDiff
|
||||||
|
|
@ -534,13 +534,13 @@ elif defined(JS):
|
||||||
|
|
||||||
proc getTimezone(): int = result = newDate().getTimezoneOffset()
|
proc getTimezone(): int = result = newDate().getTimezoneOffset()
|
||||||
|
|
||||||
proc getDateStr*(): string {.rtl, extern: "nt$1", tags: [FTime].} =
|
proc getDateStr*(): string {.rtl, extern: "nt$1", tags: [TimeEffect].} =
|
||||||
## gets the current date as a string of the format ``YYYY-MM-DD``.
|
## gets the current date as a string of the format ``YYYY-MM-DD``.
|
||||||
var ti = getLocalTime(getTime())
|
var ti = getLocalTime(getTime())
|
||||||
result = $ti.year & '-' & intToStr(ord(ti.month)+1, 2) &
|
result = $ti.year & '-' & intToStr(ord(ti.month)+1, 2) &
|
||||||
'-' & intToStr(ti.monthday, 2)
|
'-' & intToStr(ti.monthday, 2)
|
||||||
|
|
||||||
proc getClockStr*(): string {.rtl, extern: "nt$1", tags: [FTime].} =
|
proc getClockStr*(): string {.rtl, extern: "nt$1", tags: [TimeEffect].} =
|
||||||
## gets the current clock time as a string of the format ``HH:MM:SS``.
|
## gets the current clock time as a string of the format ``HH:MM:SS``.
|
||||||
var ti = getLocalTime(getTime())
|
var ti = getLocalTime(getTime())
|
||||||
result = intToStr(ti.hour, 2) & ':' & intToStr(ti.minute, 2) &
|
result = intToStr(ti.hour, 2) & ':' & intToStr(ti.minute, 2) &
|
||||||
|
|
@ -669,7 +669,7 @@ proc format_token(info: TTimeInfo, token: string, buf: var string) =
|
||||||
of "":
|
of "":
|
||||||
discard
|
discard
|
||||||
else:
|
else:
|
||||||
raise newException(EInvalidValue, "Invalid format string: " & token)
|
raise newException(ValueError, "Invalid format string: " & token)
|
||||||
|
|
||||||
|
|
||||||
proc format*(info: TTimeInfo, f: string): string =
|
proc format*(info: TTimeInfo, f: string): string =
|
||||||
|
|
|
||||||
|
|
@ -218,7 +218,7 @@ proc add*(result: var string, n: PXmlNode, indent = 0, indWidth = 2) =
|
||||||
result.add("<!-- ")
|
result.add("<!-- ")
|
||||||
result.addEscaped(n.fText)
|
result.addEscaped(n.fText)
|
||||||
result.add(" -->")
|
result.add(" -->")
|
||||||
of xnCDATA:
|
of xnCData:
|
||||||
result.add("<![CDATA[")
|
result.add("<![CDATA[")
|
||||||
result.add(n.fText)
|
result.add(n.fText)
|
||||||
result.add("]]>")
|
result.add("]]>")
|
||||||
|
|
|
||||||
|
|
@ -596,7 +596,7 @@ proc rawAlloc(a: var TMemRegion, requestedSize: int): pointer =
|
||||||
result = addr(c.data)
|
result = addr(c.data)
|
||||||
sysAssert((cast[ByteAddress](result) and (MemAlign-1)) == 0, "rawAlloc 13")
|
sysAssert((cast[ByteAddress](result) and (MemAlign-1)) == 0, "rawAlloc 13")
|
||||||
if a.root == nil: a.root = bottom
|
if a.root == nil: a.root = bottom
|
||||||
add(a, a.root, cast[ByteAddress](result), cast[TAddress](result)+%size)
|
add(a, a.root, cast[ByteAddress](result), cast[ByteAddress](result)+%size)
|
||||||
sysAssert(isAccessible(a, result), "rawAlloc 14")
|
sysAssert(isAccessible(a, result), "rawAlloc 14")
|
||||||
sysAssert(allocInv(a), "rawAlloc: end")
|
sysAssert(allocInv(a), "rawAlloc: end")
|
||||||
when logAlloc: cprintf("rawAlloc: %ld %p\n", requestedSize, result)
|
when logAlloc: cprintf("rawAlloc: %ld %p\n", requestedSize, result)
|
||||||
|
|
@ -769,7 +769,7 @@ template instantiateForRegion(allocator: expr) =
|
||||||
result = interiorAllocatedPtr(allocator, p)
|
result = interiorAllocatedPtr(allocator, p)
|
||||||
|
|
||||||
proc isAllocatedPtr*(p: pointer): bool =
|
proc isAllocatedPtr*(p: pointer): bool =
|
||||||
let p = cast[pointer](cast[ByteAddress](p)-%TAddress(sizeof(TCell)))
|
let p = cast[pointer](cast[ByteAddress](p)-%ByteAddress(sizeof(TCell)))
|
||||||
result = isAllocatedPtr(allocator, p)
|
result = isAllocatedPtr(allocator, p)
|
||||||
|
|
||||||
proc deallocOsPages = deallocOsPages(allocator)
|
proc deallocOsPages = deallocOsPages(allocator)
|
||||||
|
|
|
||||||
|
|
@ -111,11 +111,11 @@ proc addZCT(s: var TCellSeq, c: PCell) {.noinline.} =
|
||||||
|
|
||||||
proc cellToUsr(cell: PCell): pointer {.inline.} =
|
proc cellToUsr(cell: PCell): pointer {.inline.} =
|
||||||
# convert object (=pointer to refcount) to pointer to userdata
|
# convert object (=pointer to refcount) to pointer to userdata
|
||||||
result = cast[pointer](cast[ByteAddress](cell)+%TAddress(sizeof(TCell)))
|
result = cast[pointer](cast[ByteAddress](cell)+%ByteAddress(sizeof(TCell)))
|
||||||
|
|
||||||
proc usrToCell(usr: pointer): PCell {.inline.} =
|
proc usrToCell(usr: pointer): PCell {.inline.} =
|
||||||
# convert pointer to userdata to object (=pointer to refcount)
|
# convert pointer to userdata to object (=pointer to refcount)
|
||||||
result = cast[PCell](cast[ByteAddress](usr)-%TAddress(sizeof(TCell)))
|
result = cast[PCell](cast[ByteAddress](usr)-%ByteAddress(sizeof(TCell)))
|
||||||
|
|
||||||
proc canbeCycleRoot(c: PCell): bool {.inline.} =
|
proc canbeCycleRoot(c: PCell): bool {.inline.} =
|
||||||
result = ntfAcyclic notin c.typ.flags
|
result = ntfAcyclic notin c.typ.flags
|
||||||
|
|
|
||||||
|
|
@ -644,7 +644,7 @@ type
|
||||||
InternalHigh*: PULONG
|
InternalHigh*: PULONG
|
||||||
Offset*: DWORD
|
Offset*: DWORD
|
||||||
OffsetHigh*: DWORD
|
OffsetHigh*: DWORD
|
||||||
hEvent*: THANDLE
|
hEvent*: THandle
|
||||||
|
|
||||||
POVERLAPPED* = ptr TOVERLAPPED
|
POVERLAPPED* = ptr TOVERLAPPED
|
||||||
|
|
||||||
|
|
@ -666,14 +666,14 @@ const
|
||||||
WSAETIMEDOUT* = 10060
|
WSAETIMEDOUT* = 10060
|
||||||
ERROR_NETNAME_DELETED* = 64
|
ERROR_NETNAME_DELETED* = 64
|
||||||
|
|
||||||
proc CreateIoCompletionPort*(FileHandle: THANDLE, ExistingCompletionPort: THANDLE,
|
proc CreateIoCompletionPort*(FileHandle: THandle, ExistingCompletionPort: THandle,
|
||||||
CompletionKey: DWORD,
|
CompletionKey: DWORD,
|
||||||
NumberOfConcurrentThreads: DWORD): THANDLE{.stdcall,
|
NumberOfConcurrentThreads: DWORD): THandle{.stdcall,
|
||||||
dynlib: "kernel32", importc: "CreateIoCompletionPort".}
|
dynlib: "kernel32", importc: "CreateIoCompletionPort".}
|
||||||
|
|
||||||
proc GetQueuedCompletionStatus*(CompletionPort: THandle,
|
proc GetQueuedCompletionStatus*(CompletionPort: THandle,
|
||||||
lpNumberOfBytesTransferred: PDWORD, lpCompletionKey: PULONG,
|
lpNumberOfBytesTransferred: PDWORD, lpCompletionKey: PULONG,
|
||||||
lpOverlapped: ptr POverlapped,
|
lpOverlapped: ptr POVERLAPPED,
|
||||||
dwMilliseconds: DWORD): WINBOOL{.stdcall,
|
dwMilliseconds: DWORD): WINBOOL{.stdcall,
|
||||||
dynlib: "kernel32", importc: "GetQueuedCompletionStatus".}
|
dynlib: "kernel32", importc: "GetQueuedCompletionStatus".}
|
||||||
|
|
||||||
|
|
@ -699,7 +699,7 @@ var
|
||||||
|
|
||||||
proc WSAIoctl*(s: TSocketHandle, dwIoControlCode: DWORD, lpvInBuffer: pointer,
|
proc WSAIoctl*(s: TSocketHandle, dwIoControlCode: DWORD, lpvInBuffer: pointer,
|
||||||
cbInBuffer: DWORD, lpvOutBuffer: pointer, cbOutBuffer: DWORD,
|
cbInBuffer: DWORD, lpvOutBuffer: pointer, cbOutBuffer: DWORD,
|
||||||
lpcbBytesReturned: PDword, lpOverlapped: POVERLAPPED,
|
lpcbBytesReturned: PDWORD, lpOverlapped: POVERLAPPED,
|
||||||
lpCompletionRoutine: POVERLAPPED_COMPLETION_ROUTINE): cint
|
lpCompletionRoutine: POVERLAPPED_COMPLETION_ROUTINE): cint
|
||||||
{.stdcall, importc: "WSAIoctl", dynlib: "Ws2_32.dll".}
|
{.stdcall, importc: "WSAIoctl", dynlib: "Ws2_32.dll".}
|
||||||
|
|
||||||
|
|
@ -709,16 +709,16 @@ type
|
||||||
buf*: cstring
|
buf*: cstring
|
||||||
|
|
||||||
proc WSARecv*(s: TSocketHandle, buf: ptr TWSABuf, bufCount: DWORD,
|
proc WSARecv*(s: TSocketHandle, buf: ptr TWSABuf, bufCount: DWORD,
|
||||||
bytesReceived, flags: PDWORD, lpOverlapped: POverlapped,
|
bytesReceived, flags: PDWORD, lpOverlapped: POVERLAPPED,
|
||||||
completionProc: POVERLAPPED_COMPLETION_ROUTINE): cint {.
|
completionProc: POVERLAPPED_COMPLETION_ROUTINE): cint {.
|
||||||
stdcall, importc: "WSARecv", dynlib: "Ws2_32.dll".}
|
stdcall, importc: "WSARecv", dynlib: "Ws2_32.dll".}
|
||||||
|
|
||||||
proc WSASend*(s: TSocketHandle, buf: ptr TWSABuf, bufCount: DWORD,
|
proc WSASend*(s: TSocketHandle, buf: ptr TWSABuf, bufCount: DWORD,
|
||||||
bytesSent: PDWord, flags: DWORD, lpOverlapped: POverlapped,
|
bytesSent: PDWORD, flags: DWORD, lpOverlapped: POVERLAPPED,
|
||||||
completionProc: POVERLAPPED_COMPLETION_ROUTINE): cint {.
|
completionProc: POVERLAPPED_COMPLETION_ROUTINE): cint {.
|
||||||
stdcall, importc: "WSASend", dynlib: "Ws2_32.dll".}
|
stdcall, importc: "WSASend", dynlib: "Ws2_32.dll".}
|
||||||
|
|
||||||
proc get_osfhandle*(fd:TFileHandle): THandle {.
|
proc get_osfhandle*(fd:FileHandle): THandle {.
|
||||||
importc: "_get_osfhandle", header:"<io.h>".}
|
importc: "_get_osfhandle", header:"<io.h>".}
|
||||||
|
|
||||||
proc getSystemTimes*(lpIdleTime, lpKernelTime,
|
proc getSystemTimes*(lpIdleTime, lpKernelTime,
|
||||||
|
|
|
||||||
1
todo.txt
1
todo.txt
|
|
@ -1,7 +1,6 @@
|
||||||
version 0.9.6
|
version 0.9.6
|
||||||
=============
|
=============
|
||||||
|
|
||||||
- fix bug #1320
|
|
||||||
- fix tflowvar codegen test
|
- fix tflowvar codegen test
|
||||||
- split idetools into separate tool
|
- split idetools into separate tool
|
||||||
- split docgen into separate tool
|
- split docgen into separate tool
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue