renamefest

This commit is contained in:
Araq
2014-08-23 01:43:49 +02:00
parent fc0fda14ae
commit 2f43fdb837
62 changed files with 342 additions and 343 deletions

View File

@@ -799,7 +799,7 @@ type
loc*: TLoc
TPair*{.final.} = object
key*, val*: PObject
key*, val*: RootRef
TPairSeq* = seq[TPair]
TTable*{.final.} = object # the same as table[PObject] of PObject
@@ -808,7 +808,7 @@ type
TIdPair*{.final.} = object
key*: PIdObj
val*: PObject
val*: RootRef
TIdPairSeq* = seq[TIdPair]
TIdTable*{.final.} = object # the same as table[PIdent] of PObject
@@ -835,7 +835,7 @@ type
counter*: int
data*: TNodePairSeq
TObjectSeq* = seq[PObject]
TObjectSeq* = seq[RootRef]
TObjectSet*{.final.} = object
counter*: int
data*: TObjectSeq

View File

@@ -14,7 +14,7 @@
import
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
# Convert a tree into its YAML representation; this is used by the
# 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
# ----------------------- node sets: ---------------------------------------
proc objectSetContains*(t: TObjectSet, obj: PObject): bool
proc objectSetContains*(t: TObjectSet, obj: RootRef): bool
# 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
proc objectSetContainsOrIncl*(t: var TObjectSet, obj: PObject): bool
proc objectSetContainsOrIncl*(t: var TObjectSet, obj: RootRef): bool
# more are not needed ...
# ----------------------- (key, val)-Hashtables ----------------------------
proc tablePut*(t: var TTable, key, val: PObject)
proc tableGet*(t: TTable, key: PObject): PObject
proc tablePut*(t: var TTable, key, val: RootRef)
proc tableGet*(t: TTable, key: RootRef): RootRef
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,
comparator: TCmpProc): PObject
proc tableSearch*(t: TTable, key, closure: RootRef,
comparator: TCmpProc): RootRef
# return val as soon as comparator returns true; if this never happens,
# nil is returned
@@ -79,9 +79,9 @@ proc debug*(n: PType) {.deprecated.}
proc debug*(n: PNode) {.deprecated.}
# --------------------------- ident tables ----------------------------------
proc idTableGet*(t: TIdTable, key: PIdObj): PObject
proc idTableGet*(t: TIdTable, key: int): PObject
proc idTablePut*(t: var TIdTable, key: PIdObj, val: PObject)
proc idTableGet*(t: TIdTable, key: PIdObj): RootRef
proc idTableGet*(t: TIdTable, key: int): RootRef
proc idTablePut*(t: var TIdTable, key: PIdObj, val: RootRef)
proc idTableHasObjectAsKey*(t: TIdTable, key: PIdObj): bool
# checks if `t` contains the `key` (compared by the pointer value, not only
# `key`'s id)
@@ -196,7 +196,7 @@ proc getSymFromList(list: PNode, ident: PIdent, start: int = 0): PSym =
else: internalError(list.info, "getSymFromList")
result = nil
proc hashNode(p: PObject): THash =
proc hashNode(p: RootRef): THash =
result = hash(cast[pointer](p))
proc mustRehash(length, counter: int): bool =
@@ -283,7 +283,7 @@ proc symToYamlAux(n: PSym, marker: var TIntSet, indent: int,
result = toRope("null")
elif containsOrIncl(marker, n.id):
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:
var ast = treeToYamlAux(n.ast, marker, indent + 2, maxRecDepth - 1)
result = ropeConstr(indent, [toRope("kind"),
@@ -304,7 +304,7 @@ proc typeToYamlAux(n: PType, marker: var TIntSet, indent: int,
result = toRope("null")
elif containsOrIncl(marker, n.id):
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:
if sonsLen(n) > 0:
result = toRope("[")
@@ -469,7 +469,7 @@ proc nextTry(h, maxHash: THash): THash =
# generates each int in range(maxHash) exactly once (see any text on
# 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
var h: THash = hashNode(obj) and high(t.data) # start with real hash value
while t.data[h] != nil:
@@ -478,7 +478,7 @@ proc objectSetContains(t: TObjectSet, obj: PObject): bool =
h = nextTry(h, high(t.data))
result = false
proc objectSetRawInsert(data: var TObjectSeq, obj: PObject) =
proc objectSetRawInsert(data: var TObjectSeq, obj: RootRef) =
var h: THash = hashNode(obj) and high(data)
while data[h] != nil:
assert(data[h] != obj)
@@ -493,12 +493,12 @@ proc objectSetEnlarge(t: var TObjectSet) =
if t.data[i] != nil: objectSetRawInsert(n, t.data[i])
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)
objectSetRawInsert(t.data, obj)
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:
var h: THash = hashNode(obj) and high(t.data)
while true:
@@ -516,7 +516,7 @@ proc objectSetContainsOrIncl(t: var TObjectSet, obj: PObject): bool =
inc(t.counter)
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
while t.data[h].key != nil:
if t.data[h].key == key:
@@ -524,8 +524,8 @@ proc tableRawGet(t: TTable, key: PObject): int =
h = nextTry(h, high(t.data))
result = -1
proc tableSearch(t: TTable, key, closure: PObject,
comparator: TCmpProc): PObject =
proc tableSearch(t: TTable, key, closure: RootRef,
comparator: TCmpProc): RootRef =
var h: THash = hashNode(key) and high(t.data) # start with real hash value
while t.data[h].key != nil:
if t.data[h].key == key:
@@ -535,12 +535,12 @@ proc tableSearch(t: TTable, key, closure: PObject,
h = nextTry(h, high(t.data))
result = nil
proc tableGet(t: TTable, key: PObject): PObject =
proc tableGet(t: TTable, key: RootRef): RootRef =
var index = tableRawGet(t, key)
if index >= 0: result = t.data[index].val
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)
while data[h].key != nil:
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)
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)
if index >= 0:
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
else: result = false
proc idTableGet(t: TIdTable, key: PIdObj): PObject =
proc idTableGet(t: TIdTable, key: PIdObj): RootRef =
var index = idTableRawGet(t, key.id)
if index >= 0: result = t.data[index].val
else: result = nil
proc idTableGet(t: TIdTable, key: int): PObject =
proc idTableGet(t: TIdTable, key: int): RootRef =
var index = idTableRawGet(t, key)
if index >= 0: result = t.data[index].val
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):
if t.data[i].key != nil:
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
h = key.id and high(data)
while data[h].key != nil:
@@ -765,7 +765,7 @@ proc idTableRawInsert(data: var TIdPairSeq, key: PIdObj, val: PObject) =
data[h].key = key
data[h].val = val
proc idTablePut(t: var TIdTable, key: PIdObj, val: PObject) =
proc idTablePut(t: var TIdTable, key: PIdObj, val: RootRef) =
var
index: int
n: TIdPairSeq
@@ -784,7 +784,7 @@ proc idTablePut(t: var TIdTable, key: PIdObj, val: PObject) =
idTableRawInsert(t.data, key, val)
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):
if not isNil(t.data[i].key): yield (t.data[i].key, t.data[i].val)

View File

@@ -428,10 +428,10 @@ proc getRecordDesc(m: BModule, typ: PType, name: PRope,
var hasField = false
var attribute: PRope =
if tfPacked in typ.flags: toRope(CC[ccompiler].packedPragma)
if tfPacked in typ.flags: toRope(CC[cCompiler].packedPragma)
else: nil
result = ropecg(m, CC[ccompiler].structStmtFmt,
result = ropecg(m, CC[cCompiler].structStmtFmt,
[structOrUnion(typ), name, attribute])
if typ.kind == tyObject:

View File

@@ -149,7 +149,7 @@ proc getUniqueType*(key: PType): PType =
idTablePut(gTypeTable[k], key, 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
result = idTableGet(tab, key)
if (result == nil) and (tab.counter > 0):

View File

@@ -284,7 +284,7 @@ proc processSwitch(switch, arg: string, pass: TCmdLinePass, info: TLineInfo) =
if pass in {passCmd2, passPP} and not options.gNoBabelPath:
expectArg(switch, arg, pass, info)
let path = processPath(arg, notRelativeToProj=true)
babelpath(path, info)
babelPath(path, info)
of "nobabelpath":
expectNoArg(switch, arg, pass, info)
options.gNoBabelPath = true

View File

@@ -102,7 +102,7 @@ proc crcFromFile(filename: string): TCrc32 =
const
bufSize = 8000 # don't use 8K for the memory allocator!
var
bin: TFile
bin: File
result = InitCrc32
if not open(bin, filename):
return # not equal if file does not exist

View File

@@ -374,11 +374,11 @@ proc genItem(d: PDoc, n, nameNode: PNode, k: TSymKind) =
cleanPlainSymbol = renderPlainSymbolName(nameNode)
complexSymbol = complexName(k, n, cleanPlainSymbol)
plainSymbolRope = toRope(cleanPlainSymbol)
plainSymbolEncRope = toRope(URLEncode(cleanPlainSymbol))
plainSymbolEncRope = toRope(URLencode(cleanPlainSymbol))
itemIDRope = toRope(d.id)
symbolOrId = d.newUniquePlainSymbol(complexSymbol)
symbolOrIdRope = symbolOrId.toRope
symbolOrIdEncRope = URLEncode(symbolOrId).toRope
symbolOrIdEncRope = URLencode(symbolOrId).toRope
var seeSrcRope: PRope = nil
let docItemSeeSrc = getConfigVar("doc.item.seesrc")

View File

@@ -26,7 +26,7 @@ proc close(p: PPassContext, n: PNode): PNode =
writeOutput(g.doc, g.module.filename, HtmlExt, useWarning)
try:
generateIndex(g.doc)
except EIO:
except IOError:
discard
proc processNode(c: PPassContext, n: PNode): PNode =

View File

@@ -551,7 +551,7 @@ proc footprint(filename: string): TCrc32 =
proc externalFileChanged(filename: string): bool =
var crcFile = toGeneratedFile(filename.withPackageName, "crc")
var currentCrc = int(footprint(filename))
var f: TFile
var f: File
if open(f, crcFile, fmRead):
var line = newStringOfCap(40)
if not f.readLine(line): line = "0"

View File

@@ -15,7 +15,7 @@ import
hashes, strutils
type
TIdObj* = object of TObject
TIdObj* = object of RootObj
id*: int # unique id; use this for comparisons and not the pointers
PIdObj* = ref TIdObj

View File

@@ -53,7 +53,7 @@ proc saveMaxIds*(project: string) =
f.close()
proc loadMaxIds*(project: string) =
var f: TFile
var f: File
if open(f, project.toGid, fmRead):
var line = newStringOfCap(20)
if f.readLine(line):

View File

@@ -128,7 +128,7 @@ type
obj: PType
PEnv = ref TEnv
TEnv {.final.} = object of TObject
TEnv {.final.} = object of RootObj
attachedNode, replacementNode: PNode
createdVar: PNode # if != nil it is a used environment; for closure
# iterators this can be 'envParam.env'

View File

@@ -429,9 +429,9 @@ proc getNumber(L: var TLexer): TToken =
elif result.tokType == tkInt16Lit and
(result.iNumber < int16.low or result.iNumber > int16.high):
lexMessage(L, errNumberOutOfRange, result.literal)
except EInvalidValue:
except ValueError:
lexMessage(L, errInvalidNumber, result.literal)
except EOverflow, EOutOfRange:
except OverflowError, EOutOfRange:
lexMessage(L, errNumberOutOfRange, result.literal)
L.bufpos = endpos
@@ -519,7 +519,7 @@ proc handleCRLF(L: var TLexer, pos: int): int =
lexMessagePos(L, hintLineTooLong, pos)
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)
addSourceLine(L.fileIdx, line)

View File

@@ -12,7 +12,7 @@
import os
type
PListEntry* = ref TListEntry
TListEntry* = object of TObject
TListEntry* = object of RootObj
prev*, next*: PListEntry
TStrEntry* = object of TListEntry

View File

@@ -21,9 +21,9 @@ type
llsString, # stream encapsulates a string
llsFile, # stream encapsulates a file
llsStdIn # stream encapsulates stdin
TLLStream* = object of TObject
TLLStream* = object of RootObj
kind*: TLLStreamKind # accessible for low-level access (lexbase uses this)
f*: TFile
f*: File
s*: string
rd*, wr*: int # for string streams
lineOffset*: int # for fake stdin line numbers
@@ -31,8 +31,8 @@ type
PLLStream* = ref TLLStream
proc llStreamOpen*(data: string): PLLStream
proc llStreamOpen*(f: var TFile): PLLStream
proc llStreamOpen*(filename: string, mode: TFileMode): PLLStream
proc llStreamOpen*(f: var File): PLLStream
proc llStreamOpen*(filename: string, mode: FileMode): PLLStream
proc llStreamOpen*(): PLLStream
proc llStreamOpenStdIn*(): PLLStream
proc llStreamClose*(s: PLLStream)
@@ -50,12 +50,12 @@ proc llStreamOpen(data: string): PLLStream =
result.s = data
result.kind = llsString
proc llStreamOpen(f: var TFile): PLLStream =
proc llStreamOpen(f: var File): PLLStream =
new(result)
result.f = f
result.kind = llsFile
proc llStreamOpen(filename: string, mode: TFileMode): PLLStream =
proc llStreamOpen(filename: string, mode: FileMode): PLLStream =
new(result)
result.kind = llsFile
if not open(result.f, filename, mode): result = nil

View File

@@ -260,7 +260,7 @@ proc createWrapperProc(f: PNode; threadParam, argsParam: PSym;
threadLocalBarrier = addLocalVar(varSection2, nil, argsParam.owner,
barrier.typ, barrier)
body.add varSection2
body.add callCodeGenProc("barrierEnter", threadLocalBarrier.newSymNode)
body.add callCodegenProc("barrierEnter", threadLocalBarrier.newSymNode)
var threadLocalProm: PSym
if spawnKind == srByVar:
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,
"owner", fv.info), threadParam.newSymNode)
body.add callCodeGenProc("nimArgsPassingDone", threadParam.newSymNode)
body.add callCodegenProc("nimArgsPassingDone", threadParam.newSymNode)
if spawnKind == srByVar:
body.add newAsgnStmt(genDeref(threadLocalProm.newSymNode), call)
elif fv != nil:
@@ -288,11 +288,11 @@ proc createWrapperProc(f: PNode; threadParam, argsParam: PSym;
if barrier == nil:
# by now 'fv' is shared and thus might have beeen overwritten! we need
# to use the thread-local view instead:
body.add callCodeGenProc("nimFlowVarSignal", threadLocalProm.newSymNode)
body.add callCodegenProc("nimFlowVarSignal", threadLocalProm.newSymNode)
else:
body.add call
if barrier != nil:
body.add callCodeGenProc("barrierLeave", threadLocalBarrier.newSymNode)
body.add callCodegenProc("barrierLeave", threadLocalBarrier.newSymNode)
var params = newNodeI(nkFormalParams, f.info)
params.add emptyNode
@@ -542,7 +542,7 @@ proc wrapProcForSpawn*(owner: PSym; spawnExpr: PNode; retType: PType;
# create flowVar:
result.add newFastAsgnStmt(fvField, callProc(spawnExpr[2]))
if barrier == nil:
result.add callCodeGenProc("nimFlowVarCreateCondVar", fvField)
result.add callCodegenProc("nimFlowVarCreateCondVar", fvField)
elif spawnKind == srByVar:
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,
varSection, varInit, call,
barrierAsExpr, fvAsExpr, spawnKind)
result.add callCodeGenProc("nimSpawn", wrapper.newSymNode,
result.add callCodegenProc("nimSpawn", wrapper.newSymNode,
genAddrOf(scratchObj.newSymNode))
if spawnKind == srFlowVar: result.add fvField

View File

@@ -177,7 +177,7 @@ proc includeModule*(s: PSym, fileIdx: int32): PNode {.procvar.} =
proc `==^`(a, b: string): bool =
try:
result = sameFile(a, b)
except EOS:
except OSError:
result = false
proc compileSystemModule* =

View File

@@ -468,8 +468,8 @@ type
TErrorOutputs* = set[TErrorOutput]
ERecoverableError* = object of EInvalidValue
ESuggestDone* = object of E_Base
ERecoverableError* = object of ValueError
ESuggestDone* = object of Exception
const
InvalidFileIDX* = int32(-1)
@@ -858,7 +858,7 @@ proc sourceLine*(i: TLineInfo): PRope =
try:
for line in lines(i.toFullPath):
addSourceLine i.fileIndex, line.string
except EIO:
except IOError:
discard
internalAssert i.fileIndex < fileInfos.len
# can happen if the error points to EOF:

View File

@@ -37,7 +37,7 @@ const
NewLines* = {CR, LF}
type
TBaseLexer* = object of TObject
TBaseLexer* = object of RootObj
bufpos*: int
buf*: cstring
bufLen*: int # length of buffer in characters

View File

@@ -40,7 +40,7 @@ proc handleCmdLine() =
if gProjectName != "":
try:
gProjectFull = canonicalizePath(gProjectName)
except EOS:
except OSError:
gProjectFull = gProjectName
var p = splitFile(gProjectFull)
gProjectPath = p.dir

View File

@@ -295,7 +295,7 @@ proc completeGeneratedFilePath*(f: string, createSubDir: bool = true): string =
createDir(subdir)
when noTimeMachine:
excludeDirFromTimeMachine(subdir)
except EOS:
except OSError:
writeln(stdout, "cannot create directory: " & subdir)
quit(1)
result = joinPath(subdir, tail)

View File

@@ -84,7 +84,7 @@ proc openParser*(p: var TParser, fileIdx: int32, inputStream: PLLStream,
proc openParser*(p: var TParser, filename: string, inputStream: PLLStream,
strongSpaces=false) =
openParser(p, filename.fileInfoIdx, inputstream, strongSpaces)
openParser(p, filename.fileInfoIdx, inputStream, strongSpaces)
proc closeParser(p: var TParser) =
## Close a parser, freeing up its resources.

View File

@@ -16,7 +16,7 @@ import
nimsets, syntaxes, times, rodread, idgen
type
TPassContext* = object of TObject # the pass's context
TPassContext* = object of RootObj # the pass's context
fromCache*: bool # true if created by "openCached"
PPassContext* = ref TPassContext

View File

@@ -38,7 +38,7 @@ proc overwriteFiles*() =
f.write line
f.write("\L")
f.close
except EIO:
except IOError:
rawMessage(errCannotOpenFile, newFile)
proc `=~`(s: string, a: openArray[string]): bool =

View File

@@ -41,7 +41,7 @@ proc differ*(line: string, a, b: int, x: string): bool =
let y = line[a..b]
result = cmpIgnoreStyle(y, x) == 0 and y != x
proc replaceDeprecated*(info: TlineInfo; oldSym, newSym: PSym) =
proc replaceDeprecated*(info: TLineInfo; oldSym, newSym: PSym) =
loadFile(info)
let line = gSourceFiles[info.fileIndex].lines[info.line-1]

View File

@@ -1306,7 +1306,7 @@ proc renderTree(n: PNode, renderFlags: TRenderFlags = {}): string =
proc renderModule(n: PNode, filename: string,
renderFlags: TRenderFlags = {}) =
var
f: TFile
f: File
g: TSrcGen
initSrcGen(g, renderFlags)
for i in countup(0, sonsLen(n) - 1):

View File

@@ -121,7 +121,7 @@ type
r*: string # writers use this
offset*: int # readers use this
TRodReader* = object of TObject
TRodReader* = object of RootObj
pos: int # position; used for parsing
s: cstring # mmap'ed file contents
options: TOptions
@@ -503,7 +503,7 @@ proc processCompilerProcs(r: PRodReader, module: PSym) =
idTablePut(r.syms, s, 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
inc(r.pos, 2) # skip "(\10"
inc(r.line)
@@ -659,7 +659,7 @@ proc newRodReader(modfilename: string, crc: TCrc32,
new(result)
try:
result.memfile = memfiles.open(modfilename)
except EOS:
except OSError:
return nil
result.files = @[]
result.modDeps = @[]
@@ -916,7 +916,7 @@ initIdTable(gTypeTable)
initStrTable(rodCompilerprocs)
# viewer:
proc writeNode(f: TFile; n: PNode) =
proc writeNode(f: File; n: PNode) =
f.write("(")
if n != nil:
f.write($n.kind)
@@ -947,7 +947,7 @@ proc writeNode(f: TFile; n: PNode) =
writeNode(f, n.sons[i])
f.write(")")
proc writeSym(f: TFile; s: PSym) =
proc writeSym(f: File; s: PSym) =
if s == nil:
f.write("{}\n")
return
@@ -985,7 +985,7 @@ proc writeSym(f: TFile; s: PSym) =
f.writeNode(s.ast)
f.write("}\n")
proc writeType(f: TFile; t: PType) =
proc writeType(f: File; t: PType) =
if t == nil:
f.write("[]\n")
return

View File

@@ -422,7 +422,7 @@ proc addStmt(w: PRodWriter, n: PNode) =
proc writeRod(w: PRodWriter) =
processStacks(w, true)
var f: TFile
var f: File
if not open(f, completeGeneratedFilePath(changeFileExt(
w.filename.withPackageName, RodExt)),
fmWrite):

View File

@@ -64,7 +64,7 @@ type
# copy the format strings
# though it is not necessary)
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
left*, right*: PRope
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 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]
while len(stack) > 0:
var it = pop(stack)
@@ -228,7 +228,7 @@ proc writeRope*(f: TFile, c: PRope) =
write(f, it.data)
proc writeRope*(head: PRope, filename: string, useWarning = false) =
var f: TFile
var f: File
if open(f, filename, fmWrite):
if head != nil: writeRope(f, head)
close(f)
@@ -299,7 +299,7 @@ proc appf(c: var PRope, frmt: TFormatStr, args: varargs[PRope]) =
const
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.length > bufSize:
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)
proc ropeEqualsFile(r: PRope, f: string): bool =
var bin: TFile
var bin: File
result = open(bin, f)
if not result:
return # not equal if file does not exist

View File

@@ -683,9 +683,9 @@ proc getConstExpr(m: PSym, n: PNode): PNode =
result = evalIs(n, a)
else:
result = magicCall(m, n)
except EOverflow:
except OverflowError:
localError(n.info, errOverOrUnderflow)
except EDivByZero:
except DivByZeroError:
localError(n.info, errConstantDivisionByZero)
of nkAddr:
var a = getConstExpr(m, n.sons[0])

View File

@@ -55,7 +55,7 @@ proc annotateType*(n: PNode, t: PType) =
else:
globalError(n.info, "() must have an object or tuple type")
of nkBracket:
if x.kind in {tyArrayConstr, tyArray, tySequence, tyOpenarray}:
if x.kind in {tyArrayConstr, tyArray, tySequence, tyOpenArray}:
n.typ = t
for m in n: annotateType(m, x.elemType)
else:

View File

@@ -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
# prevent direct assignments to the monotonic variable:
let slot = c.getSlot(n[0].sym)
slot.blackListed = true
slot.blacklisted = true
invalidateFacts(c.guards, n[0])
analyseSons(c, n)
addAsgnFact(c.guards, n[0], n[1])
@@ -464,6 +464,6 @@ proc liftParallel*(owner: PSym; n: PNode): PNode =
result = newNodeI(nkStmtList, n.info)
generateAliasChecks(a, result)
result.add varSection
result.add callCodeGenProc("openBarrier", barrier)
result.add callCodegenProc("openBarrier", barrier)
result.add transformSpawn(owner, body, barrier)
result.add callCodeGenProc("closeBarrier", barrier)
result.add callCodegenProc("closeBarrier", barrier)

View File

@@ -44,7 +44,7 @@ proc parseTopLevelStmt*(p: var TParsers): PNode
proc parseFile(fileIdx: int32): PNode =
var
p: TParsers
f: TFile
f: File
let filename = fileIdx.toFullPath
if not open(f, filename):
rawMessage(errCannotOpenFile, filename)

View File

@@ -24,13 +24,13 @@ proc getProcHeader*(sym: PSym): string
proc base*(t: PType): PType
# ------------------- type iterator: ----------------------------------------
type
TTypeIter* = proc (t: PType, closure: PObject): bool {.nimcall.} # true if iteration should stop
TTypeMutator* = proc (t: PType, closure: PObject): PType {.nimcall.} # copy t and mutate it
TTypeIter* = proc (t: PType, closure: RootRef): bool {.nimcall.} # true if iteration should stop
TTypeMutator* = proc (t: PType, closure: RootRef): PType {.nimcall.} # copy t and mutate it
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`.
proc mutateType*(t: PType, iter: TTypeMutator, closure: PObject): PType
proc mutateType*(t: PType, iter: TTypeMutator, closure: RootRef): PType
# Returns result of `iter`.
type
@@ -161,9 +161,9 @@ proc enumHasHoles(t: PType): bool =
result = b.kind == tyEnum and tfEnumHasHoles in b.flags
proc iterOverTypeAux(marker: var TIntSet, t: PType, iter: TTypeIter,
closure: PObject): bool
closure: RootRef): bool
proc iterOverNode(marker: var TIntSet, n: PNode, iter: TTypeIter,
closure: PObject): bool =
closure: RootRef): bool =
if n != nil:
case n.kind
of nkNone..nkNilLit:
@@ -175,7 +175,7 @@ proc iterOverNode(marker: var TIntSet, n: PNode, iter: TTypeIter,
if result: return
proc iterOverTypeAux(marker: var TIntSet, t: PType, iter: TTypeIter,
closure: PObject): bool =
closure: RootRef): bool =
result = false
if t == nil: return
result = iter(t, closure)
@@ -190,7 +190,7 @@ proc iterOverTypeAux(marker: var TIntSet, t: PType, iter: TTypeIter,
if result: return
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()
result = iterOverTypeAux(marker, t, iter, closure)
@@ -354,9 +354,9 @@ proc canFormAcycle(typ: PType): bool =
result = canFormAcycleAux(marker, typ, typ.id)
proc mutateTypeAux(marker: var TIntSet, t: PType, iter: TTypeMutator,
closure: PObject): PType
closure: RootRef): PType
proc mutateNode(marker: var TIntSet, n: PNode, iter: TTypeMutator,
closure: PObject): PNode =
closure: RootRef): PNode =
result = nil
if n != nil:
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))
proc mutateTypeAux(marker: var TIntSet, t: PType, iter: TTypeMutator,
closure: PObject): PType =
closure: RootRef): PType =
result = nil
if t == nil: return
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)
assert(result != nil)
proc mutateType(t: PType, iter: TTypeMutator, closure: PObject): PType =
proc mutateType(t: PType, iter: TTypeMutator, closure: RootRef): PType =
var marker = initIntSet()
result = mutateTypeAux(marker, t, iter, closure)
@@ -1283,7 +1283,7 @@ proc getSize(typ: PType): BiggestInt =
result = computeSize(typ)
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:
return t.n == nil

View File

@@ -33,6 +33,6 @@ proc opSlurp*(file: string, info: TLineInfo, module: PSym): string =
# the module dependencies are accurate:
appendToModule(module, newNode(nkIncludeStmt, info, @[
newStrNode(nkStrLit, filename)]))
except EIO:
except IOError:
localError(info, errCannotOpenFile, file)
result = ""

View File

@@ -97,7 +97,7 @@ type
TNimSymKinds* = set[TNimrodSymKind]
type
TNimrodIdent* = object of TObject
TNimrodIdent* = object of RootObj
## represents a Nimrod identifier in the AST
TNimrodSymbol {.final.} = object # hidden
@@ -596,7 +596,7 @@ proc `pragma=`*(someProc: PNimrodNode; val: PNimrodNode){.compileTime.}=
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)
proc body*(someProc: PNimrodNode): PNimrodNode {.compileTime.} =
@@ -608,7 +608,7 @@ proc body*(someProc: PNimrodNode): PNimrodNode {.compileTime.} =
of nnkForStmt:
return someProc.last
else:
badNodeKind someproc.kind, "body"
badNodeKind someProc.kind, "body"
proc `body=`*(someProc: PNimrodNode, val: PNimrodNode) {.compileTime.} =
case someProc.kind

View File

@@ -23,7 +23,7 @@ type
gtTagStart, gtTagEnd, gtKey, gtValue, gtRawData, gtAssembler,
gtPreprocessor, gtDirective, gtCommand, gtRule, gtHyperlink, gtLabel,
gtReference, gtOther
TGeneralTokenizer* = object of TObject
TGeneralTokenizer* = object of RootObj
kind*: TTokenClass
start*, length*: int
buf: cstring

View File

@@ -118,7 +118,7 @@ type
line*, col*: int # line and column of the token
TTokenSeq = seq[TToken]
TLexer = object of TObject
TLexer = object of RootObj
buf*: cstring
bufpos*: int
line*, col*, baseIndent*: int
@@ -273,7 +273,7 @@ type
findFile: TFindFileHandler # How to find files.
PSharedState = ref TSharedState
TRstParser = object of TObject
TRstParser = object of RootObj
idx*: int
tok*: TTokenSeq
s*: PSharedState
@@ -282,7 +282,7 @@ type
line*, col*: int
hasToc*: bool
EParseError* = object of EInvalidValue
EParseError* = object of ValueError
proc whichMsgClass*(k: TMsgKind): TMsgClass =
## returns which message class `k` belongs to.

View File

@@ -42,7 +42,7 @@ type
TMetaEnum* = enum
metaNone, metaTitle, metaSubtitle, metaAuthor, metaVersion
TRstGenerator* = object of TObject
TRstGenerator* = object of RootObj
target*: TOutputTarget
config*: PStringTable
splitAfter*: int # split too long entries in the TOC
@@ -1011,7 +1011,7 @@ proc formatNamedVars*(frmt: string, varnames: openArray[string],
inc(i)
if i > L-1 or frmt[i] notin {'0'..'9'}: break
if j > high(varvalues) + 1:
raise newException(EInvalidValue, "invalid index: " & $j)
raise newException(ValueError, "invalid index: " & $j)
num = j
add(result, varvalues[j - 1])
of 'A'..'Z', 'a'..'z', '\x80'..'\xFF':
@@ -1024,13 +1024,13 @@ proc formatNamedVars*(frmt: string, varnames: openArray[string],
if idx >= 0:
add(result, varvalues[idx])
else:
raise newException(EInvalidValue, "unknown substitution var: " & id)
raise newException(ValueError, "unknown substitution var: " & id)
of '{':
var id = ""
inc(i)
while frmt[i] != '}':
if frmt[i] == '\0':
raise newException(EInvalidValue, "'}' expected")
raise newException(ValueError, "'}' expected")
add(id, frmt[i])
inc(i)
inc(i) # skip }
@@ -1038,9 +1038,9 @@ proc formatNamedVars*(frmt: string, varnames: openArray[string],
var idx = getVarIdx(varnames, id)
if idx >= 0: add(result, varvalues[idx])
else:
raise newException(EInvalidValue, "unknown substitution var: " & id)
raise newException(ValueError, "unknown substitution var: " & id)
else:
raise newException(EInvalidValue, "unknown substitution: $" & $frmt[i])
raise newException(ValueError, "unknown substitution: $" & $frmt[i])
var start = i
while i < L:
if frmt[i] != '$': inc(i)

View File

@@ -69,7 +69,7 @@ proc smartBinarySearch*[T](a: openArray[T], key: T): int =
const
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
## 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))
@@ -98,7 +98,7 @@ proc lowerBound*[T](a: openarray[T], key: T, cmp: proc(x,y: T): int {.closure.})
else:
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,
cmp: proc (x, y: T): int {.closure.}, order: TSortOrder) =
template `<-` (a, b: expr) =
@@ -184,7 +184,7 @@ proc sort*[T](a: var openArray[T],
dec(m, 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
## may explode.
result = @[]

View File

@@ -93,7 +93,7 @@ proc XMLencode*(s: string): string =
for i in 0..len(s)-1: addXmlChar(result, s[i])
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
methodNone, ## no REQUEST_METHOD environment variable
methodPost, ## query uses the POST method
@@ -107,18 +107,18 @@ proc cgiError*(msg: string) {.noreturn.} =
raise e
proc getEncodedData(allowedMethods: set[TRequestMethod]): string =
case getenv("REQUEST_METHOD").string
case getEnv("REQUEST_METHOD").string
of "POST":
if methodPost notin allowedMethods:
cgiError("'REQUEST_METHOD' 'POST' is not supported")
var L = parseInt(getenv("CONTENT_LENGTH").string)
var L = parseInt(getEnv("CONTENT_LENGTH").string)
result = newString(L)
if readBuffer(stdin, addr(result[0]), L) != L:
cgiError("cannot read from stdin")
of "GET":
if methodGet notin allowedMethods:
cgiError("'REQUEST_METHOD' 'GET' is not supported")
result = getenv("QUERY_STRING").string
result = getEnv("QUERY_STRING").string
else:
if methodNone notin allowedMethods:
cgiError("'REQUEST_METHOD' must be 'POST' or 'GET'")
@@ -192,131 +192,131 @@ proc validateData*(data: PStringTable, validKeys: varargs[string]) =
proc getContentLength*(): string =
## returns contents of the ``CONTENT_LENGTH`` environment variable
return getenv("CONTENT_LENGTH").string
return getEnv("CONTENT_LENGTH").string
proc getContentType*(): string =
## returns contents of the ``CONTENT_TYPE`` environment variable
return getenv("CONTENT_Type").string
return getEnv("CONTENT_Type").string
proc getDocumentRoot*(): string =
## returns contents of the ``DOCUMENT_ROOT`` environment variable
return getenv("DOCUMENT_ROOT").string
return getEnv("DOCUMENT_ROOT").string
proc getGatewayInterface*(): string =
## returns contents of the ``GATEWAY_INTERFACE`` environment variable
return getenv("GATEWAY_INTERFACE").string
return getEnv("GATEWAY_INTERFACE").string
proc getHttpAccept*(): string =
## returns contents of the ``HTTP_ACCEPT`` environment variable
return getenv("HTTP_ACCEPT").string
return getEnv("HTTP_ACCEPT").string
proc getHttpAcceptCharset*(): string =
## returns contents of the ``HTTP_ACCEPT_CHARSET`` environment variable
return getenv("HTTP_ACCEPT_CHARSET").string
return getEnv("HTTP_ACCEPT_CHARSET").string
proc getHttpAcceptEncoding*(): string =
## returns contents of the ``HTTP_ACCEPT_ENCODING`` environment variable
return getenv("HTTP_ACCEPT_ENCODING").string
return getEnv("HTTP_ACCEPT_ENCODING").string
proc getHttpAcceptLanguage*(): string =
## returns contents of the ``HTTP_ACCEPT_LANGUAGE`` environment variable
return getenv("HTTP_ACCEPT_LANGUAGE").string
return getEnv("HTTP_ACCEPT_LANGUAGE").string
proc getHttpConnection*(): string =
## returns contents of the ``HTTP_CONNECTION`` environment variable
return getenv("HTTP_CONNECTION").string
return getEnv("HTTP_CONNECTION").string
proc getHttpCookie*(): string =
## returns contents of the ``HTTP_COOKIE`` environment variable
return getenv("HTTP_COOKIE").string
return getEnv("HTTP_COOKIE").string
proc getHttpHost*(): string =
## returns contents of the ``HTTP_HOST`` environment variable
return getenv("HTTP_HOST").string
return getEnv("HTTP_HOST").string
proc getHttpReferer*(): string =
## returns contents of the ``HTTP_REFERER`` environment variable
return getenv("HTTP_REFERER").string
return getEnv("HTTP_REFERER").string
proc getHttpUserAgent*(): string =
## returns contents of the ``HTTP_USER_AGENT`` environment variable
return getenv("HTTP_USER_AGENT").string
return getEnv("HTTP_USER_AGENT").string
proc getPathInfo*(): string =
## returns contents of the ``PATH_INFO`` environment variable
return getenv("PATH_INFO").string
return getEnv("PATH_INFO").string
proc getPathTranslated*(): string =
## returns contents of the ``PATH_TRANSLATED`` environment variable
return getenv("PATH_TRANSLATED").string
return getEnv("PATH_TRANSLATED").string
proc getQueryString*(): string =
## returns contents of the ``QUERY_STRING`` environment variable
return getenv("QUERY_STRING").string
return getEnv("QUERY_STRING").string
proc getRemoteAddr*(): string =
## returns contents of the ``REMOTE_ADDR`` environment variable
return getenv("REMOTE_ADDR").string
return getEnv("REMOTE_ADDR").string
proc getRemoteHost*(): string =
## returns contents of the ``REMOTE_HOST`` environment variable
return getenv("REMOTE_HOST").string
return getEnv("REMOTE_HOST").string
proc getRemoteIdent*(): string =
## returns contents of the ``REMOTE_IDENT`` environment variable
return getenv("REMOTE_IDENT").string
return getEnv("REMOTE_IDENT").string
proc getRemotePort*(): string =
## returns contents of the ``REMOTE_PORT`` environment variable
return getenv("REMOTE_PORT").string
return getEnv("REMOTE_PORT").string
proc getRemoteUser*(): string =
## returns contents of the ``REMOTE_USER`` environment variable
return getenv("REMOTE_USER").string
return getEnv("REMOTE_USER").string
proc getRequestMethod*(): string =
## returns contents of the ``REQUEST_METHOD`` environment variable
return getenv("REQUEST_METHOD").string
return getEnv("REQUEST_METHOD").string
proc getRequestURI*(): string =
## returns contents of the ``REQUEST_URI`` environment variable
return getenv("REQUEST_URI").string
return getEnv("REQUEST_URI").string
proc getScriptFilename*(): string =
## returns contents of the ``SCRIPT_FILENAME`` environment variable
return getenv("SCRIPT_FILENAME").string
return getEnv("SCRIPT_FILENAME").string
proc getScriptName*(): string =
## returns contents of the ``SCRIPT_NAME`` environment variable
return getenv("SCRIPT_NAME").string
return getEnv("SCRIPT_NAME").string
proc getServerAddr*(): string =
## returns contents of the ``SERVER_ADDR`` environment variable
return getenv("SERVER_ADDR").string
return getEnv("SERVER_ADDR").string
proc getServerAdmin*(): string =
## returns contents of the ``SERVER_ADMIN`` environment variable
return getenv("SERVER_ADMIN").string
return getEnv("SERVER_ADMIN").string
proc getServerName*(): string =
## returns contents of the ``SERVER_NAME`` environment variable
return getenv("SERVER_NAME").string
return getEnv("SERVER_NAME").string
proc getServerPort*(): string =
## returns contents of the ``SERVER_PORT`` environment variable
return getenv("SERVER_PORT").string
return getEnv("SERVER_PORT").string
proc getServerProtocol*(): string =
## returns contents of the ``SERVER_PROTOCOL`` environment variable
return getenv("SERVER_PROTOCOL").string
return getEnv("SERVER_PROTOCOL").string
proc getServerSignature*(): string =
## returns contents of the ``SERVER_SIGNATURE`` environment variable
return getenv("SERVER_SIGNATURE").string
return getEnv("SERVER_SIGNATURE").string
proc getServerSoftware*(): string =
## returns contents of the ``SERVER_SOFTWARE`` environment variable
return getenv("SERVER_SOFTWARE").string
return getEnv("SERVER_SOFTWARE").string
proc setTestData*(keysvalues: varargs[string]) =
## fills the appropriate environment variables to test your CGI application.
@@ -325,7 +325,7 @@ proc setTestData*(keysvalues: varargs[string]) =
##
## .. code-block:: Nimrod
## setTestData("name", "Hanz", "password", "12345")
putenv("REQUEST_METHOD", "GET")
putEnv("REQUEST_METHOD", "GET")
var i = 0
var query = ""
while i < keysvalues.len:
@@ -334,7 +334,7 @@ proc setTestData*(keysvalues: varargs[string]) =
add(query, URLencode(keysvalues[i+1]))
add(query, '&')
inc(i, 2)
putenv("QUERY_STRING", query)
putEnv("QUERY_STRING", query)
proc writeContentType*() =
## call this before starting to send your HTML data to `stdout`. This

View File

@@ -129,7 +129,7 @@ proc mget*[A](s: var TSet[A], key: A): var A =
assert s.isValid, "The set needs to be initialized."
var index = rawGet(s, 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 =
## Returns true iff `key` is in `s`.

View File

@@ -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.
var index = rawGet(t, key)
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 =
## 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.
var index = rawGet(t, key)
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 =
## 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.
var index = rawGet(t, key)
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 =
## returns true iff `key` is in the table `t`.

View File

@@ -47,7 +47,7 @@ proc setCookie*(key, value: string, expires: TTimeInfo,
## **Note:** UTC is assumed as the timezone for ``expires``.
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:
var tim = TTime(int(getTime()) + 76 * (60 * 60 * 24))
@@ -56,4 +56,4 @@ when isMainModule:
echo parseCookies("uid=1; kp=2")

View File

@@ -529,7 +529,7 @@ type
of JArray:
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.} =
## raises an `EJsonParsingError` exception.
@@ -741,7 +741,7 @@ proc delete*(obj: PJsonNode, key: string) =
if obj.fields[i].key == key:
obj.fields.delete(i)
return
raise newException(EInvalidIndex, "key not in object")
raise newException(IndexError, "key not in object")
proc copy*(p: PJsonNode): PJsonNode =
## Performs a deep copy of `a`.
@@ -942,7 +942,7 @@ when not defined(js):
## Parses `file` into a `PJsonNode`.
var stream = newFileStream(filename, fmRead)
if stream == nil:
raise newException(EIO, "cannot read from file: " & filename)
raise newException(IOError, "cannot read from file: " & filename)
result = parseJson(stream, filename)
else:
from math import `mod`

View File

@@ -25,7 +25,7 @@ const
#
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.
bufpos*: int ## the current position within the buffer
buf*: cstring ## the buffer itself

View File

@@ -278,11 +278,11 @@ else:
proc `mod`*(x, y: float): float =
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`.
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`.
result = a[random(a.low..a.len)]

View File

@@ -35,7 +35,7 @@ type
handle: cint
proc mapMem*(m: var TMemFile, mode: TFileMode = fmRead,
proc mapMem*(m: var TMemFile, mode: FileMode = fmRead,
mappedSize = -1, offset = 0): pointer =
var readonly = mode == fmRead
when defined(windows):
@@ -71,7 +71,7 @@ proc unmapMem*(f: var TMemFile, p: pointer, size: int) =
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 =
## 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

View File

@@ -29,14 +29,14 @@ else:
include "system/ansi_c"
type
FReadEnv* = object of FReadIO ## effect that denotes a read
FReadEnv* = object of ReadIOEffect ## effect that denotes a read
## 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
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
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
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.
if len(msg) == 0:
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:
raise newException(EOS, msg)
raise newException(OSError, msg)
{.pop.}
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,
## 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.msg = osErrorMsg(errorCode)
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
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
## binary content.
const
bufSize = 8192 # 8K buffer
var
a, b: TFile
a, b: File
if not open(a, path1): return false
if not open(b, path2):
close(a)
@@ -951,7 +951,7 @@ proc setFilePermissions*(filename: string, permissions: set[TFilePermission]) {.
if res2 == - 1'i32: osError(osLastError())
proc copyFile*(source, dest: string) {.rtl, extern: "nos$1",
tags: [FReadIO, FWriteIO].} =
tags: [ReadIOEffect, FWriteIO].} =
## Copies a file from `source` to `dest`.
##
## 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)
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.
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 NoFakeVars:
@@ -1034,7 +1034,7 @@ proc removeFile*(file: string) {.rtl, extern: "nos$1", tags: [FWriteDir].} =
raise newException(EOS, $strerror(errno))
proc execShellCmd*(command: string): int {.rtl, extern: "nos$1",
tags: [FExecIO].} =
tags: [ExecIOEffect].} =
## Executes a `shell command`:idx:.
##
## Command has the form 'program args' where args are the command
@@ -1076,7 +1076,7 @@ when defined(windows):
while true:
var eend = strEnd(e)
add(environment, $e)
e = cast[WideCString](cast[TAddress](eend)+2)
e = cast[WideCString](cast[ByteAddress](eend)+2)
if eend[1].int == 0: break
discard freeEnvironmentStringsW(env)
else:
@@ -1364,7 +1364,7 @@ proc createDir*(dir: string) {.rtl, extern: "nos$1", tags: [FWriteDir].} =
rawCreateDir(dir)
proc copyDir*(source, dest: string) {.rtl, extern: "nos$1",
tags: [FWriteIO, FReadIO].} =
tags: [WriteIOEffect, FReadIO].} =
## Copies a directory from `source` to `dest`.
##
## 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,
ignorePermissionErrors = true) {.rtl, extern: "nos$1",
tags: [FWriteIO, FReadIO].} =
tags: [WriteIOEffect, FReadIO].} =
## Copies a directory from `source` to `dest` preserving file permissions.
##
## If this fails, `EOS` is raised. This is a wrapper proc around `copyDir()
@@ -1657,13 +1657,13 @@ elif defined(windows):
var
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.
if isNil(ownArgv): ownArgv = parseCmdLine($getCommandLine())
result = ownArgv.len-1
proc paramStr*(i: int): TaintedString {.rtl, extern: "nos$1",
tags: [FReadIO].} =
tags: [ReadIOEffect].} =
# Docstring in nimdoc block.
if isNil(ownArgv): ownArgv = parseCmdLine($getCommandLine())
return TaintedString(ownArgv[i])
@@ -1739,7 +1739,7 @@ when defined(macosx):
proc getExecPath2(c: cstring, size: var cuint32): bool {.
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.
##
## This procedure will resolve symlinks.
@@ -1795,12 +1795,12 @@ proc getApplicationDir*(): string {.rtl, extern: "nos$1", deprecated.} =
## instead.
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.
## **Note**: This does not work reliably on BSD.
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.
when defined(windows):
winlean.sleep(int32(milsecs))
@@ -1811,7 +1811,7 @@ proc sleep*(milsecs: int) {.rtl, extern: "nos$1", tags: [FTime].} =
discard posix.nanosleep(a, b)
proc getFileSize*(file: string): BiggestInt {.rtl, extern: "nos$1",
tags: [FReadIO].} =
tags: [ReadIOEffect].} =
## returns the file size of `file`. Can raise ``EOS``.
when defined(windows):
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_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
## handle.
##
@@ -1960,7 +1960,7 @@ proc getFileInfo*(handle: TFileHandle): FileInfo =
osError(osLastError())
rawToFormalFileInfo(rawInfo, result)
proc getFileInfo*(file: TFile): FileInfo =
proc getFileInfo*(file: File): FileInfo =
result = getFileInfo(file.fileHandle())
proc getFileInfo*(path: string, followSymlink = true): FileInfo =

View File

@@ -24,10 +24,10 @@ when defined(linux):
import linux
type
TProcess = object of TObject
TProcess = object of RootObj
when defined(windows):
fProcessHandle: THandle
inHandle, outHandle, errHandle: TFileHandle
inHandle, outHandle, errHandle: FileHandle
id: THandle
else:
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".}
proc execProcess*(command: string,
args: openarray[string] = [],
args: openArray[string] = [],
env: PStringTable = nil,
options: set[TProcessOption] = {poStdErrToStdOut,
poUsePath,
poEvalCommand}): TaintedString {.
rtl, extern: "nosp$1",
tags: [FExecIO, FReadIO].}
tags: [ExecIOEffect, FReadIO].}
## A convenience procedure that executes ``command`` with ``startProcess``
## and returns its output as a string.
## WARNING: this function uses poEvalCommand by default for backward compatibility.
## 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,
## error streams are inherited from the calling process. This operation
## is also often called `system`:idx:.
@@ -125,7 +125,7 @@ proc startProcess*(command: string,
args: openArray[string] = [],
env: PStringTable = nil,
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
## process's working directory. If ``workingDir == ""`` the current directory
## 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] = {
poStdErrToStdOut, poUsePath}): PProcess {.
tags: [FExecIO, FReadEnv], deprecated.} =
tags: [ExecIOEffect, FReadEnv], deprecated.} =
## Deprecated - use `startProcess` directly.
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
## 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: [].} =
## 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``.
result = p.inHandle
proc outputHandle*(p: PProcess): TFileHandle {.rtl, extern: "nosp$1",
proc outputHandle*(p: PProcess): FileHandle {.rtl, extern: "nosp$1",
tags: [].} =
## 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``.
result = p.outHandle
proc errorHandle*(p: PProcess): TFileHandle {.rtl, extern: "nosp$1",
proc errorHandle*(p: PProcess): FileHandle {.rtl, extern: "nosp$1",
tags: [].} =
## 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],
options = {poStdErrToStdOut, poParentStreams},
n = countProcessors()): int {.rtl, extern: "nosp$1",
tags: [FExecIO, FTime, FReadEnv]} =
tags: [ExecIOEffect, FTime, FReadEnv]} =
## executes the commands `cmds` in parallel. Creates `n` processes
## that execute in parallel. The highest return value of all processes
## is returned.
@@ -294,7 +294,7 @@ proc select*(readfds: var seq[PProcess], timeout = 500): int
when not defined(useNimRtl):
proc execProcess(command: string,
args: openarray[string] = [],
args: openArray[string] = [],
env: PStringTable = nil,
options: set[TProcessOption] = {poStdErrToStdOut,
poUsePath,
@@ -406,16 +406,16 @@ when defined(Windows) and not defined(useNimRtl):
he = ho
else:
createPipeHandles(he, si.hStdError)
result.inHandle = TFileHandle(hi)
result.outHandle = TFileHandle(ho)
result.errHandle = TFileHandle(he)
result.inHandle = FileHandle(hi)
result.outHandle = FileHandle(ho)
result.errHandle = FileHandle(he)
else:
si.hStdError = getStdHandle(STD_ERROR_HANDLE)
si.hStdInput = getStdHandle(STD_INPUT_HANDLE)
si.hStdOutput = getStdHandle(STD_OUTPUT_HANDLE)
result.inHandle = TFileHandle(si.hStdInput)
result.outHandle = TFileHandle(si.hStdOutput)
result.errHandle = TFileHandle(si.hStdError)
result.inHandle = FileHandle(si.hStdInput)
result.outHandle = FileHandle(si.hStdOutput)
result.errHandle = FileHandle(si.hStdError)
var cmdl: cstring
if poEvalCommand in options:
@@ -916,7 +916,7 @@ elif not defined(useNimRtl):
proc execCmdEx*(command: string, options: set[TProcessOption] = {
poStdErrToStdOut, poUsePath}): tuple[
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
## exit code and returns both.
var p = startCmd(command, options)

View File

@@ -28,7 +28,7 @@ type
cmdLongoption, ## a long option ``--option`` detected
cmdShortOption ## a short option ``-c`` detected
TOptParser* =
object of TObject ## this object implements the command line parser
object of RootObj ## this object implements the command line parser
cmd: string
pos: int
inShortState: bool

View File

@@ -227,7 +227,7 @@ proc parseInt*(s: string, number: var int, start = 0): int {.
result = parseBiggestInt(s, res, start)
if (sizeof(int) <= 4) and
((res < low(int)) or (res > high(int))):
raise newException(EOverflow, "overflow")
raise newException(OverflowError, "overflow")
else:
number = int(res)
@@ -376,7 +376,7 @@ iterator interpolatedFragments*(s: string): tuple[kind: TInterpolatedKind,
break
dec nesting
of '\0':
raise newException(EInvalidValue,
raise newException(ValueError,
"Expected closing '}': " & s[i..s.len])
else: discard
inc j
@@ -392,7 +392,7 @@ iterator interpolatedFragments*(s: string): tuple[kind: TInterpolatedKind,
inc i # skip $
kind = ikDollar
else:
raise newException(EInvalidValue,
raise newException(ValueError,
"Unable to parse a varible name at " & s[i..s.len])
else:
while j < s.len and s[j] != '$': inc j

View File

@@ -377,14 +377,14 @@ proc socketError*(socket: TSocket, err: int = -1, async = false) =
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.
## ``Backlog`` specifies the maximum length of the
## queue of pending connections.
if listen(socket.fd, cint(backlog)) < 0'i32: osError(osLastError())
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 =
## 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):
osError(osLastError())
else:
raise newException(EOS, $gai_strerror(gaiResult))
raise newException(OSError, $gai_strerror(gaiResult))
proc bindAddr*(socket: TSocket, port = TPort(0), address = "") {.
tags: [FReadIO].} =
tags: [ReadIOEffect].} =
## binds an address/port number to a socket.
## Use address string in dotted decimal form like "a.b.c.d"
## 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_addr.s_addr = sockets.htonl(INADDR_ANY)
if bindSocket(socket.fd, cast[ptr TSockAddr](addr(name)),
sizeof(name).TSocklen) < 0'i32:
sizeof(name).TSockLen) < 0'i32:
osError(osLastError())
else:
var hints: Taddrinfo
var aiList: ptr Taddrinfo = nil
var hints: TAddrInfo
var aiList: ptr TAddrInfo = nil
hints.ai_family = toInt(AF_INET)
hints.ai_socktype = toInt(SOCK_STREAM)
hints.ai_protocol = toInt(IPPROTO_TCP)
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())
proc getSockName*(socket: TSocket): TPort =
@@ -460,7 +460,7 @@ proc getSockName*(socket: TSocket): TPort =
name.sin_family = posix.AF_INET
#name.sin_port = htons(cint16(port))
#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)),
addr(namelen)) == -1'i32:
osError(osLastError())
@@ -470,7 +470,7 @@ template acceptAddrPlain(noClientRet, successRet: expr,
sslImplementation: stmt): stmt {.immediate.} =
assert(client != nil)
var sockAddress: Tsockaddr_in
var addrLen = sizeof(sockAddress).TSocklen
var addrLen = sizeof(sockAddress).TSockLen
var sock = accept(server.fd, cast[ptr TSockAddr](addr(sockAddress)),
addr(addrLen))
@@ -506,7 +506,7 @@ template acceptAddrPlain(noClientRet, successRet: expr,
return successRet
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
## is made sets ``client`` to the client socket and ``address`` to the address
## of the connecting client.
@@ -601,7 +601,7 @@ when defined(ssl):
acceptAddrPlain(AcceptNoClient, AcceptSuccess):
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
## socket.
##
@@ -612,7 +612,7 @@ proc accept*(server: TSocket, client: var TSocket) {.tags: [FReadIO].} =
acceptAddr(server, client, addrDummy)
proc acceptAddr*(server: TSocket): tuple[client: TSocket, address: string] {.
deprecated, tags: [FReadIO].} =
deprecated, tags: [ReadIOEffect].} =
## Slightly different version of ``acceptAddr``.
##
## **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)
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.
new(result)
var address = ""
@@ -640,7 +640,7 @@ proc close*(socket: TSocket) =
if socket.isSSL:
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
## which the service name specified by ``name`` matches the s_name 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)
else:
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.aliases = cstringArrayToSeq(s.s_aliases)
result.port = TPort(s.s_port)
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
## which the port specified by ``port`` matches the s_port member and the
## 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)
else:
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.aliases = cstringArrayToSeq(s.s_aliases)
result.port = TPort(s.s_port)
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.
var myaddr: TInAddr
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.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.
when defined(Windows):
var s = winlean.gethostbyname(name)
@@ -723,21 +723,21 @@ proc getHostByName*(name: string): Thostent {.tags: [FReadIO].} =
result.length = int(s.h_length)
proc getSockOptInt*(socket: TSocket, level, optname: int): int {.
tags: [FReadIO].} =
tags: [ReadIOEffect].} =
## getsockopt for integer options.
var res: cint
var size = sizeof(res).TSocklen
var size = sizeof(res).TSockLen
if getsockopt(socket.fd, cint(level), cint(optname),
addr(res), addr(size)) < 0'i32:
osError(osLastError())
result = int(res)
proc setSockOptInt*(socket: TSocket, level, optname, optval: int) {.
tags: [FWriteIO].} =
tags: [WriteIOEffect].} =
## setsockopt for integer options.
var value = cint(optval)
if setsockopt(socket.fd, cint(level), cint(optname), addr(value),
sizeof(value).TSocklen) < 0'i32:
sizeof(value).TSockLen) < 0'i32:
osError(osLastError())
proc toCInt(opt: TSOBool): cint =
@@ -751,33 +751,33 @@ proc toCInt(opt: TSOBool): cint =
of OptReuseAddr: SO_REUSEADDR
proc getSockOpt*(socket: TSocket, opt: TSOBool, level = SOL_SOCKET): bool {.
tags: [FReadIO].} =
tags: [ReadIOEffect].} =
## Retrieves option ``opt`` as a boolean value.
var res: cint
var size = sizeof(res).TSocklen
var size = sizeof(res).TSockLen
if getsockopt(socket.fd, cint(level), toCInt(opt),
addr(res), addr(size)) < 0'i32:
osError(osLastError())
result = res != 0
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``.
var valuei = cint(if value: 1 else: 0)
if setsockopt(socket.fd, cint(level), toCInt(opt), addr(valuei),
sizeof(valuei).TSocklen) < 0'i32:
sizeof(valuei).TSockLen) < 0'i32:
osError(osLastError())
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
## 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
## not do it.
##
## If ``socket`` is an SSL socket a handshake will be automatically performed.
var hints: Taddrinfo
var aiList: ptr Taddrinfo = nil
var hints: TAddrInfo
var aiList: ptr TAddrInfo = nil
hints.ai_family = toInt(af)
hints.ai_socktype = toInt(SOCK_STREAM)
hints.ai_protocol = toInt(IPPROTO_TCP)
@@ -787,7 +787,7 @@ proc connect*(socket: TSocket, address: string, port = TPort(0),
var lastError: TOSErrorCode
var it = aiList
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
break
else: lastError = osLastError()
@@ -830,7 +830,7 @@ proc connect*(socket: TSocket, address: string, port = TPort(0),
OSError()
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.
##
## 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
## whenever the socket successfully connects to a server.
var hints: Taddrinfo
var aiList: ptr Taddrinfo = nil
var hints: TAddrInfo
var aiList: ptr TAddrInfo = nil
hints.ai_family = toInt(af)
hints.ai_socktype = toInt(SOCK_STREAM)
hints.ai_protocol = toInt(IPPROTO_TCP)
@@ -850,7 +850,7 @@ proc connectAsync*(socket: TSocket, name: string, port = TPort(0),
var lastError: TOSErrorCode
var it = aiList
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:
success = true
break
@@ -915,7 +915,7 @@ when defined(ssl):
else:
SSLError("Socket is not an SSL socket.")
proc timeValFromMilliseconds(timeout = 500): Ttimeval =
proc timeValFromMilliseconds(timeout = 500): TTimeval =
if timeout != -1:
var seconds = timeout div 1000
result.tv_sec = seconds.int32
@@ -962,7 +962,7 @@ proc checkBuffer(readfds: var seq[TSocket]): int =
readfds = res
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
## sockets that are ready to be read from, written to, or which have errors.
## If there are none; 0 is returned.
@@ -975,7 +975,7 @@ proc select*(readfds, writefds, exceptfds: var seq[TSocket],
if buffersFilled > 0:
return buffersFilled
var tv {.noInit.}: Ttimeval = timeValFromMilliseconds(timeout)
var tv {.noInit.}: TTimeval = timeValFromMilliseconds(timeout)
var rd, wr, ex: TFdSet
var m = 0
@@ -993,12 +993,12 @@ proc select*(readfds, writefds, exceptfds: var seq[TSocket],
pruneSocketSet(exceptfds, (ex))
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.
let buffersFilled = checkBuffer(readfds)
if buffersFilled > 0:
return buffersFilled
var tv {.noInit.}: Ttimeval = timeValFromMilliseconds(timeout)
var tv {.noInit.}: TTimeval = timeValFromMilliseconds(timeout)
var rd, wr: TFdSet
var m = 0
@@ -1014,7 +1014,7 @@ proc select*(readfds, writefds: var seq[TSocket],
pruneSocketSet(writefds, (wr))
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
## 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
@@ -1022,7 +1022,7 @@ proc selectWrite*(writefds: var seq[TSocket],
##
## ``timeout`` is specified in miliseconds and ``-1`` can be specified for
## an unlimited time.
var tv {.noInit.}: Ttimeval = timeValFromMilliseconds(timeout)
var tv {.noInit.}: TTimeval = timeValFromMilliseconds(timeout)
var wr: TFdSet
var m = 0
@@ -1040,7 +1040,7 @@ proc select*(readfds: var seq[TSocket], timeout = 500): int =
let buffersFilled = checkBuffer(readfds)
if buffersFilled > 0:
return buffersFilled
var tv {.noInit.}: Ttimeval = timeValFromMilliseconds(timeout)
var tv {.noInit.}: TTimeval = timeValFromMilliseconds(timeout)
var rd: TFdSet
var m = 0
@@ -1077,7 +1077,7 @@ template retRead(flags, readBytes: int) {.dirty.} =
else:
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.
##
## **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)
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
## be larger than ``size``. For unbuffered sockets this will be ``1``.
## 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)
proc recv*(socket: TSocket, data: pointer, size: int, timeout: int): int {.
tags: [FReadIO, FTime].} =
tags: [ReadIOEffect, FTime].} =
## overload with a ``timeout`` parameter in miliseconds.
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
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:
result = 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)
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``.
##
## 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)
proc readLine*(socket: TSocket, line: var TaintedString, timeout = -1) {.
tags: [FReadIO, FTime].} =
tags: [ReadIOEffect, FTime].} =
## Reads a line of data from ``socket``.
##
## 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)
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.
##
## The values of the returned enum should be pretty self explanatory:
@@ -1344,7 +1344,7 @@ proc recvLineAsync*(socket: TSocket,
add(line.string, c)
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.
##
## The values of the returned enum should be pretty self explanatory:
@@ -1378,7 +1378,7 @@ proc readLineAsync*(socket: TSocket,
elif c == '\L': return ReadFullLine
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.
## Socket errors will result in an ``EOS`` error.
## 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.}
proc recvTimeout*(socket: TSocket, timeout: int): TaintedString {.
tags: [FReadIO], deprecated.} =
tags: [ReadIOEffect], deprecated.} =
## overloaded variant to support a ``timeout`` parameter, the ``timeout``
## parameter specifies the amount of miliseconds to wait for data on the
## socket.
@@ -1426,7 +1426,7 @@ proc recvTimeout*(socket: TSocket, timeout: int): TaintedString {.
{.pop.}
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
## and there are no messages available, `False` will be returned.
## 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,
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
## connection-less sockets (UDP sockets).
##
@@ -1493,7 +1493,7 @@ proc recvFrom*(socket: TSocket, data: var string, length: int,
# TODO: Buffered sockets
data.setLen(length)
var sockAddress: Tsockaddr_in
var addrLen = sizeof(sockAddress).TSocklen
var addrLen = sizeof(sockAddress).TSockLen
result = recvfrom(socket.fd, cstring(data), length.cint, flags.cint,
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,
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``,
## 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
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
##
## **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)
proc send*(socket: TSocket, data: pointer, size: int): int {.
tags: [FWriteIO].} =
tags: [WriteIOEffect].} =
## sends data to a socket.
when defined(ssl):
if socket.isSSL:
@@ -1560,10 +1560,10 @@ proc send*(socket: TSocket, data: pointer, size: int): int {.
const MSG_NOSIGNAL = 0
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.
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)
if sent < 0:
when defined(ssl):
@@ -1573,9 +1573,9 @@ proc send*(socket: TSocket, data: string) {.tags: [FWriteIO].} =
osError(osLastError())
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.
## 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
@@ -1614,21 +1614,21 @@ proc sendAsync*(socket: TSocket, data: string): int {.tags: [FWriteIO].} =
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,
## and instead returns ``false`` on failure.
result = send(socket, cstring(data), data.len) == data.len
proc sendTo*(socket: TSocket, address: string, port: TPort, data: pointer,
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``,
## which may be an IP address or a hostname, if a hostname is specified
## this function will try each IP of that hostname.
##
## **Note:** This proc is not available for SSL sockets.
var hints: Taddrinfo
var aiList: ptr Taddrinfo = nil
var hints: TAddrInfo
var aiList: ptr TAddrInfo = nil
hints.ai_family = toInt(af)
hints.ai_socktype = toInt(SOCK_STREAM)
hints.ai_protocol = toInt(IPPROTO_TCP)
@@ -1639,7 +1639,7 @@ proc sendTo*(socket: TSocket, address: string, port: TPort, data: pointer,
var it = aiList
while it != nil:
result = sendto(socket.fd, data, size.cint, flags.cint, it.ai_addr,
it.ai_addrlen.TSocklen)
it.ai_addrlen.TSockLen)
if result != -1'i32:
success = true
break
@@ -1648,7 +1648,7 @@ proc sendTo*(socket: TSocket, address: string, port: TPort, data: pointer,
freeaddrinfo(aiList)
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``.
result = socket.sendTo(address, port, cstring(data), data.len)
@@ -1685,7 +1685,7 @@ discard """ proc setReuseAddr*(s: TSocket) =
OSError(OSLastError()) """
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``.
##
## The ``timeout`` paremeter specifies the time in miliseconds to allow for

View File

@@ -14,13 +14,13 @@
include "system/inclrtl"
proc newEIO(msg: string): ref EIO =
proc newEIO(msg: string): ref IOError =
new(result)
result.msg = msg
type
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
## here shouldn't be used directly. They are
## accessible so that a stream implementation
@@ -30,10 +30,10 @@ type
setPositionImpl*: proc (s: PStream, pos: int) {.nimcall, tags: [], gcsafe.}
getPositionImpl*: proc (s: PStream): int {.nimcall, tags: [], gcsafe.}
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,
tags: [FWriteIO], gcsafe.}
flushImpl*: proc (s: PStream) {.nimcall, tags: [FWriteIO], gcsafe.}
tags: [WriteIOEffect], gcsafe.}
flushImpl*: proc (s: PStream) {.nimcall, tags: [WriteIOEffect], gcsafe.}
proc flush*(s: PStream) =
## flushes the buffers that the stream `s` might use.
@@ -246,7 +246,7 @@ when not defined(js):
type
PFileStream* = ref TFileStream ## a stream that encapsulates a `TFile`
TFileStream* = object of TStream
f: TFile
f: File
proc fsClose(s: PStream) =
if PFileStream(s).f != nil:
@@ -264,7 +264,7 @@ when not defined(js):
if writeBuffer(PFileStream(s).f, buffer, bufLen) != bufLen:
raise newEIO("cannot write to stream")
proc newFileStream*(f: TFile): PFileStream =
proc newFileStream*(f: File): PFileStream =
## creates a new stream from the file `f`.
new(result)
result.f = f
@@ -276,11 +276,11 @@ when not defined(js):
result.writeDataImpl = fsWriteData
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`.
## If the file cannot be opened, nil is returned. See the `system
## <system.html>`_ module for a list of available TFileMode enums.
var f: TFile
var f: File
if open(f, filename, mode): result = newFileStream(f)

View File

@@ -24,7 +24,7 @@ type
modeStyleInsensitive ## the table is style insensitive
TKeyValuePair = tuple[key, val: string]
TKeyValuePairSeq = seq[TKeyValuePair]
TStringTable* = object of TObject
TStringTable* = object of RootObj
counter: int
data: TKeyValuePairSeq
mode: TStringTableMode
@@ -110,7 +110,7 @@ proc mget*(t: PStringTable, key: string): var string {.
## ``EInvalidKey`` exception is raised.
var index = rawGet(t, key)
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".} =
## 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)
proc raiseFormatException(s: string) =
var e: ref EInvalidValue
var e: ref ValueError
new(e)
e.msg = "format string: key not found: " & s
raise e

View File

@@ -420,7 +420,7 @@ proc parseInt*(s: string): int {.noSideEffect, procvar,
## If `s` is not a valid integer, `EInvalidValue` is raised.
var L = parseutils.parseInt(s, result, 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,
rtl, extern: "nsuParseBiggestInt".} =
@@ -429,7 +429,7 @@ proc parseBiggestInt*(s: string): BiggestInt {.noSideEffect, procvar,
## If `s` is not a valid integer, `EInvalidValue` is raised.
var L = parseutils.parseBiggestInt(s, result, 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,
rtl, extern: "nsuParseFloat".} =
@@ -438,7 +438,7 @@ proc parseFloat*(s: string): float {.noSideEffect, procvar,
## ``INF``, ``-INF`` are also supported (case insensitive comparison).
var L = parseutils.parseFloat(s, result, 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,
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)
inc(i)
of '\0': break
else: raise newException(EInvalidValue, "invalid integer: " & s)
else: raise newException(ValueError, "invalid integer: " & s)
proc parseBool*(s: string): bool =
## Parses a value into a `bool`.
@@ -475,7 +475,7 @@ proc parseBool*(s: string): bool =
case normalize(s)
of "y", "yes", "true", "1", "on": result = true
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 =
## Parses an enum ``T``.
@@ -485,7 +485,7 @@ proc parseEnum*[T: enum](s: string): T =
for e in low(T)..high(T):
if cmpIgnoreStyle(s, $e) == 0:
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 =
## Parses an enum ``T``.
@@ -911,7 +911,7 @@ proc parseOctInt*(s: string): int {.noSideEffect,
result = result shl 3 or (ord(s[i]) - ord('0'))
inc(i)
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,
rtl, extern: "nsuToOct".} =
@@ -1003,7 +1003,7 @@ proc unescape*(s: string, prefix = "\"", suffix = "\""): string {.noSideEffect,
result = newStringOfCap(s.len)
var i = 0
if s[0 .. prefix.len-1] != prefix:
raise newException(EInvalidValue,
raise newException(ValueError,
"String does not start with a prefix of: " & prefix)
i.inc()
while true:
@@ -1028,7 +1028,7 @@ proc unescape*(s: string, prefix = "\"", suffix = "\""): string {.noSideEffect,
result.add(s[i])
i.inc()
if s[i .. -1] != suffix:
raise newException(EInvalidValue,
raise newException(ValueError,
"String does not end with a suffix of: " & suffix)
proc validIdentifier*(s: string): bool {.noSideEffect,
@@ -1219,7 +1219,7 @@ proc findNormalized(x: string, inArray: openArray[string]): int =
return -1
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, `$`]) {.
noSideEffect, rtl, extern: "nsuAddf".} =

View File

@@ -103,7 +103,7 @@ elif defined(JS):
toLocaleString: proc (): cstring {.tags: [], raises: [], gcsafe.}
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,
## normally in the range 0 to 59, but can
## be up to 61 to allow for leap seconds.
@@ -136,14 +136,14 @@ type
months*: int ## The number of months
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
## elapsed since 1970) with integer precission. Use epochTime for higher
## 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,
## 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,
## expressed in Coordinated Universal Time (UTC).
@@ -190,15 +190,15 @@ proc `==`*(a, b: TTime): bool {.
result = a - b == 0
when not defined(JS):
proc getTzname*(): tuple[nonDST, DST: string] {.tags: [FTime], raises: [],
proc getTzname*(): tuple[nonDST, DST: string] {.tags: [TimeEffect], raises: [],
gcsafe.}
## returns the local timezone; ``nonDST`` is the name of the local non-DST
## 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.
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
## version 0.8.10.** Use ``epochTime`` or ``cpuTime`` instead.
@@ -282,12 +282,12 @@ proc `-`*(a: TTimeInfo, interval: TTimeInterval): TTimeInfo =
result = getLocalTime(fromSeconds(t - secs))
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
## because sub-second resolution is likely to be supported (depending
## 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
## seconds. This may be more useful for benchmarking than ``epochTime``.
## 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: [].}
# strftime(s: CString, maxsize: int, fmt: CString, t: tm): int {.
# 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>",
tags: [].}
@@ -458,7 +458,7 @@ when not defined(JS):
posix_gettimeofday(a)
result = toFloat(a.tv_sec) + toFloat(a.tv_usec)*0.00_0001
elif defined(windows):
var f: winlean.TFiletime
var f: winlean.TFILETIME
getSystemTimeAsFileTime(f)
var i64 = rdFileTime(f) - epochDiff
var secs = i64 div rateDiff
@@ -534,13 +534,13 @@ elif defined(JS):
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``.
var ti = getLocalTime(getTime())
result = $ti.year & '-' & intToStr(ord(ti.month)+1, 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``.
var ti = getLocalTime(getTime())
result = intToStr(ti.hour, 2) & ':' & intToStr(ti.minute, 2) &
@@ -669,7 +669,7 @@ proc format_token(info: TTimeInfo, token: string, buf: var string) =
of "":
discard
else:
raise newException(EInvalidValue, "Invalid format string: " & token)
raise newException(ValueError, "Invalid format string: " & token)
proc format*(info: TTimeInfo, f: string): string =

View File

@@ -218,7 +218,7 @@ proc add*(result: var string, n: PXmlNode, indent = 0, indWidth = 2) =
result.add("<!-- ")
result.addEscaped(n.fText)
result.add(" -->")
of xnCDATA:
of xnCData:
result.add("<![CDATA[")
result.add(n.fText)
result.add("]]>")

View File

@@ -596,7 +596,7 @@ proc rawAlloc(a: var TMemRegion, requestedSize: int): pointer =
result = addr(c.data)
sysAssert((cast[ByteAddress](result) and (MemAlign-1)) == 0, "rawAlloc 13")
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(allocInv(a), "rawAlloc: end")
when logAlloc: cprintf("rawAlloc: %ld %p\n", requestedSize, result)
@@ -769,7 +769,7 @@ template instantiateForRegion(allocator: expr) =
result = interiorAllocatedPtr(allocator, p)
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)
proc deallocOsPages = deallocOsPages(allocator)

View File

@@ -111,11 +111,11 @@ proc addZCT(s: var TCellSeq, c: PCell) {.noinline.} =
proc cellToUsr(cell: PCell): pointer {.inline.} =
# 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.} =
# 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.} =
result = ntfAcyclic notin c.typ.flags

View File

@@ -644,7 +644,7 @@ type
InternalHigh*: PULONG
Offset*: DWORD
OffsetHigh*: DWORD
hEvent*: THANDLE
hEvent*: THandle
POVERLAPPED* = ptr TOVERLAPPED
@@ -666,14 +666,14 @@ const
WSAETIMEDOUT* = 10060
ERROR_NETNAME_DELETED* = 64
proc CreateIoCompletionPort*(FileHandle: THANDLE, ExistingCompletionPort: THANDLE,
proc CreateIoCompletionPort*(FileHandle: THandle, ExistingCompletionPort: THandle,
CompletionKey: DWORD,
NumberOfConcurrentThreads: DWORD): THANDLE{.stdcall,
NumberOfConcurrentThreads: DWORD): THandle{.stdcall,
dynlib: "kernel32", importc: "CreateIoCompletionPort".}
proc GetQueuedCompletionStatus*(CompletionPort: THandle,
lpNumberOfBytesTransferred: PDWORD, lpCompletionKey: PULONG,
lpOverlapped: ptr POverlapped,
lpOverlapped: ptr POVERLAPPED,
dwMilliseconds: DWORD): WINBOOL{.stdcall,
dynlib: "kernel32", importc: "GetQueuedCompletionStatus".}
@@ -699,7 +699,7 @@ var
proc WSAIoctl*(s: TSocketHandle, dwIoControlCode: DWORD, lpvInBuffer: pointer,
cbInBuffer: DWORD, lpvOutBuffer: pointer, cbOutBuffer: DWORD,
lpcbBytesReturned: PDword, lpOverlapped: POVERLAPPED,
lpcbBytesReturned: PDWORD, lpOverlapped: POVERLAPPED,
lpCompletionRoutine: POVERLAPPED_COMPLETION_ROUTINE): cint
{.stdcall, importc: "WSAIoctl", dynlib: "Ws2_32.dll".}
@@ -709,16 +709,16 @@ type
buf*: cstring
proc WSARecv*(s: TSocketHandle, buf: ptr TWSABuf, bufCount: DWORD,
bytesReceived, flags: PDWORD, lpOverlapped: POverlapped,
bytesReceived, flags: PDWORD, lpOverlapped: POVERLAPPED,
completionProc: POVERLAPPED_COMPLETION_ROUTINE): cint {.
stdcall, importc: "WSARecv", dynlib: "Ws2_32.dll".}
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 {.
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>".}
proc getSystemTimes*(lpIdleTime, lpKernelTime,

View File

@@ -1,7 +1,6 @@
version 0.9.6
=============
- fix bug #1320
- fix tflowvar codegen test
- split idetools into separate tool
- split docgen into separate tool