diff options
author | Araq <rumpf_a@web.de> | 2013-12-27 23:10:36 +0100 |
---|---|---|
committer | Araq <rumpf_a@web.de> | 2013-12-27 23:10:36 +0100 |
commit | 92b8fac94a7243cde785d985db3fd86b6025b079 (patch) | |
tree | edbfdbab6cf496d6a0cfe226957769c3c43d2fa9 /lib | |
parent | 706266d8b728b19fde6d69fd6ccdfb65ae7b6a17 (diff) | |
download | Nim-92b8fac94a7243cde785d985db3fd86b6025b079.tar.gz |
case consistency part 4
Diffstat (limited to 'lib')
38 files changed, 1805 insertions, 1805 deletions
diff --git a/lib/packages/docutils/highlite.nim b/lib/packages/docutils/highlite.nim index 4bfdf5e58..737780a12 100644 --- a/lib/packages/docutils/highlite.nim +++ b/lib/packages/docutils/highlite.nim @@ -321,7 +321,7 @@ proc generalStrLit(g: var TGeneralTokenizer, position: int): int = inc(pos) result = pos -proc isKeyword(x: openarray[string], y: string): int = +proc isKeyword(x: openArray[string], y: string): int = var a = 0 var b = len(x) - 1 while a <= b: @@ -335,7 +335,7 @@ proc isKeyword(x: openarray[string], y: string): int = return mid result = - 1 -proc isKeywordIgnoreCase(x: openarray[string], y: string): int = +proc isKeywordIgnoreCase(x: openArray[string], y: string): int = var a = 0 var b = len(x) - 1 while a <= b: @@ -354,7 +354,7 @@ type hasPreprocessor, hasNestedComments TTokenizerFlags = set[TTokenizerFlag] -proc clikeNextToken(g: var TGeneralTokenizer, keywords: openarray[string], +proc clikeNextToken(g: var TGeneralTokenizer, keywords: openArray[string], flags: TTokenizerFlags) = const hexChars = {'0'..'9', 'A'..'F', 'a'..'f'} diff --git a/lib/packages/docutils/rst.nim b/lib/packages/docutils/rst.nim index 6dd407155..316476ce0 100644 --- a/lib/packages/docutils/rst.nim +++ b/lib/packages/docutils/rst.nim @@ -58,10 +58,10 @@ const mwUnsupportedLanguage: "language '$1' not supported" ] -proc rstnodeToRefname*(n: PRstNode): string -proc addNodes*(n: PRstNode): string -proc getFieldValue*(n: PRstNode, fieldname: string): string -proc getArgument*(n: PRstNode): string +proc rstnodeToRefname*(n: PRSTNode): string +proc addNodes*(n: PRSTNode): string +proc getFieldValue*(n: PRSTNode, fieldname: string): string +proc getArgument*(n: PRSTNode): string # ----------------------------- scanner part -------------------------------- @@ -242,7 +242,7 @@ proc getTokens(buffer: string, skipPounds: bool, tokens: var TTokenSeq): int = inc(result) while true: inc(length) - setlen(tokens, length) + setLen(tokens, length) rawGetTok(L, tokens[length - 1]) if tokens[length - 1].kind == tkEof: break if tokens[0].kind == tkWhite: @@ -254,7 +254,7 @@ type TLevelMap = array[Char, int] TSubstitution{.final.} = object key*: string - value*: PRstNode + value*: PRSTNode TSharedState {.final.} = object options: TRstParseOptions # parsing options @@ -294,11 +294,11 @@ proc whichMsgClass*(k: TMsgKind): TMsgClass = proc defaultMsgHandler*(filename: string, line, col: int, msgkind: TMsgKind, arg: string) {.procvar.} = - let mc = msgKind.whichMsgClass - let a = messages[msgKind] % arg + let mc = msgkind.whichMsgClass + let a = messages[msgkind] % arg let message = "$1($2, $3) $4: $5" % [filename, $line, $col, $mc, a] if mc == mcError: raise newException(EParseError, message) - else: Writeln(stdout, message) + else: writeln(stdout, message) proc defaultFindFile*(filename: string): string {.procvar.} = if existsFile(filename): result = filename @@ -339,7 +339,7 @@ proc pushInd(p: var TRstParser, ind: int) = add(p.indentStack, ind) proc popInd(p: var TRstParser) = - if len(p.indentStack) > 1: setlen(p.indentStack, len(p.indentStack) - 1) + if len(p.indentStack) > 1: setLen(p.indentStack, len(p.indentStack) - 1) proc initParser(p: var TRstParser, sharedState: PSharedState) = p.indentStack = @[0] @@ -351,7 +351,7 @@ proc initParser(p: var TRstParser, sharedState: PSharedState) = p.line = 1 p.s = sharedState -proc addNodesAux(n: PRstNode, result: var string) = +proc addNodesAux(n: PRSTNode, result: var string) = if n.kind == rnLeaf: add(result, n.text) else: @@ -361,7 +361,7 @@ proc addNodes(n: PRstNode): string = result = "" addNodesAux(n, result) -proc rstnodeToRefnameAux(n: PRstNode, r: var string, b: var bool) = +proc rstnodeToRefnameAux(n: PRSTNode, r: var string, b: var bool) = if n.kind == rnLeaf: for i in countup(0, len(n.text) - 1): case n.text[i] @@ -391,7 +391,7 @@ proc rstnodeToRefname(n: PRstNode): string = var b = false rstnodeToRefnameAux(n, result, b) -proc findSub(p: var TRstParser, n: PRstNode): int = +proc findSub(p: var TRstParser, n: PRSTNode): int = var key = addNodes(n) # the spec says: if no exact match, try one without case distinction: for i in countup(0, high(p.s.subs)): @@ -402,17 +402,17 @@ proc findSub(p: var TRstParser, n: PRstNode): int = return i result = -1 -proc setSub(p: var TRstParser, key: string, value: PRstNode) = +proc setSub(p: var TRstParser, key: string, value: PRSTNode) = var length = len(p.s.subs) for i in countup(0, length - 1): if key == p.s.subs[i].key: p.s.subs[i].value = value return - setlen(p.s.subs, length + 1) + setLen(p.s.subs, length + 1) p.s.subs[length].key = key p.s.subs[length].value = value -proc setRef(p: var TRstParser, key: string, value: PRstNode) = +proc setRef(p: var TRstParser, key: string, value: PRSTNode) = var length = len(p.s.refs) for i in countup(0, length - 1): if key == p.s.refs[i].key: @@ -421,19 +421,19 @@ proc setRef(p: var TRstParser, key: string, value: PRstNode) = p.s.refs[i].value = value return - setlen(p.s.refs, length + 1) + setLen(p.s.refs, length + 1) p.s.refs[length].key = key p.s.refs[length].value = value -proc findRef(p: var TRstParser, key: string): PRstNode = +proc findRef(p: var TRstParser, key: string): PRSTNode = for i in countup(0, high(p.s.refs)): if key == p.s.refs[i].key: return p.s.refs[i].value -proc newLeaf(p: var TRstParser): PRstNode = +proc newLeaf(p: var TRstParser): PRSTNode = result = newRstNode(rnLeaf, p.tok[p.idx].symbol) -proc getReferenceName(p: var TRstParser, endStr: string): PRstNode = +proc getReferenceName(p: var TRstParser, endStr: string): PRSTNode = var res = newRstNode(rnInner) while true: case p.tok[p.idx].kind @@ -451,7 +451,7 @@ proc getReferenceName(p: var TRstParser, endStr: string): PRstNode = inc(p.idx) result = res -proc untilEol(p: var TRstParser): PRstNode = +proc untilEol(p: var TRstParser): PRSTNode = result = newRstNode(rnInner) while not (p.tok[p.idx].kind in {tkIndent, tkEof}): add(result, newLeaf(p)) @@ -479,7 +479,7 @@ proc isInlineMarkupEnd(p: TRstParser, markup: string): bool = result = false proc isInlineMarkupStart(p: TRstParser, markup: string): bool = - var d: Char + var d: char result = p.tok[p.idx].symbol == markup if not result: return # Rule 1: @@ -550,7 +550,7 @@ proc match(p: TRstParser, start: int, expr: string): bool = inc(i) result = true -proc fixupEmbeddedRef(n, a, b: PRstNode) = +proc fixupEmbeddedRef(n, a, b: PRSTNode) = var sep = - 1 for i in countdown(len(n) - 2, 0): if n.sons[i].text == "<": @@ -560,7 +560,7 @@ proc fixupEmbeddedRef(n, a, b: PRstNode) = for i in countup(0, sep - incr): add(a, n.sons[i]) for i in countup(sep + 1, len(n) - 2): add(b, n.sons[i]) -proc parsePostfix(p: var TRstParser, n: PRstNode): PRstNode = +proc parsePostfix(p: var TRstParser, n: PRSTNode): PRSTNode = result = n if isInlineMarkupEnd(p, "_"): inc(p.idx) @@ -613,9 +613,9 @@ proc matchVerbatim(p: TRstParser, start: int, expr: string): int = inc result if j < expr.len: result = 0 -proc parseSmiley(p: var TRstParser): PRstNode = +proc parseSmiley(p: var TRstParser): PRSTNode = if p.tok[p.idx].symbol[0] notin SmileyStartChars: return - for key, val in items(smilies): + for key, val in items(Smilies): let m = matchVerbatim(p, p.idx, key) if m > 0: p.idx = m @@ -634,7 +634,7 @@ proc isURL(p: TRstParser, i: int): bool = (p.tok[i+3].kind == tkWord) and (p.tok[i].symbol in ["http", "https", "ftp", "telnet", "file"]) -proc parseURL(p: var TRstParser, father: PRstNode) = +proc parseURL(p: var TRstParser, father: PRSTNode) = #if p.tok[p.idx].symbol[strStart] == '<': if isURL(p, p.idx): var n = newRstNode(rnStandaloneHyperlink) @@ -654,7 +654,7 @@ proc parseURL(p: var TRstParser, father: PRstNode) = if p.tok[p.idx].symbol == "_": n = parsePostfix(p, n) add(father, n) -proc parseBackslash(p: var TRstParser, father: PRstNode) = +proc parseBackslash(p: var TRstParser, father: PRSTNode) = assert(p.tok[p.idx].kind == tkPunct) if p.tok[p.idx].symbol == "\\\\": add(father, newRstNode(rnLeaf, "\\")) @@ -692,7 +692,7 @@ when false: if p.tok[p.idx].symbol == "_": n = parsePostfix(p, n) add(father, n) -proc parseUntil(p: var TRstParser, father: PRstNode, postfix: string, +proc parseUntil(p: var TRstParser, father: PRSTNode, postfix: string, interpretBackslash: bool) = let line = p.tok[p.idx].line @@ -723,7 +723,7 @@ proc parseUntil(p: var TRstParser, father: PRstNode, postfix: string, inc(p.idx) else: rstMessage(p, meExpected, postfix, line, col) -proc parseMarkdownCodeblock(p: var TRstParser): PRstNode = +proc parseMarkdownCodeblock(p: var TRstParser): PRSTNode = var args = newRstNode(rnDirArg) if p.tok[p.idx].kind == tkWord: add(args, newLeaf(p)) @@ -753,7 +753,7 @@ proc parseMarkdownCodeblock(p: var TRstParser): PRstNode = add(result, nil) add(result, lb) -proc parseInline(p: var TRstParser, father: PRstNode) = +proc parseInline(p: var TRstParser, father: PRSTNode) = case p.tok[p.idx].kind of tkPunct: if isInlineMarkupStart(p, "***"): @@ -797,7 +797,7 @@ proc parseInline(p: var TRstParser, father: PRstNode) = if n != nil: add(father, n) return - parseUrl(p, father) + parseURL(p, father) of tkAdornment, tkOther, tkWhite: if roSupportSmilies in p.s.options: let n = parseSmiley(p) @@ -828,7 +828,7 @@ proc getDirective(p: var TRstParser): string = else: result = "" -proc parseComment(p: var TRstParser): PRstNode = +proc parseComment(p: var TRstParser): PRSTNode = case p.tok[p.idx].kind of tkIndent, tkEof: if p.tok[p.idx].kind != tkEof and p.tok[p.idx + 1].kind == tkIndent: @@ -863,20 +863,20 @@ proc getDirKind(s: string): TDirKind = if i >= 0: result = TDirKind(i) else: result = dkNone -proc parseLine(p: var TRstParser, father: PRstNode) = +proc parseLine(p: var TRstParser, father: PRSTNode) = while True: case p.tok[p.idx].kind of tkWhite, tkWord, tkOther, tkPunct: parseInline(p, father) else: break -proc parseUntilNewline(p: var TRstParser, father: PRstNode) = +proc parseUntilNewline(p: var TRstParser, father: PRSTNode) = while True: case p.tok[p.idx].kind of tkWhite, tkWord, tkAdornment, tkOther, tkPunct: parseInline(p, father) of tkEof, tkIndent: break -proc parseSection(p: var TRstParser, result: PRstNode) -proc parseField(p: var TRstParser): PRstNode = +proc parseSection(p: var TRstParser, result: PRSTNode) +proc parseField(p: var TRstParser): PRSTNode = result = newRstNode(rnField) var col = p.tok[p.idx].col var fieldname = newRstNode(rnFieldname) @@ -892,7 +892,7 @@ proc parseField(p: var TRstParser): PRstNode = add(result, fieldname) add(result, fieldbody) -proc parseFields(p: var TRstParser): PRstNode = +proc parseFields(p: var TRstParser): PRSTNode = result = nil var atStart = p.idx == 0 and p.tok[0].symbol == ":" if (p.tok[p.idx].kind == tkIndent) and (p.tok[p.idx + 1].symbol == ":") or @@ -926,8 +926,8 @@ proc getArgument(n: PRstNode): string = if n.sons[0] == nil: result = "" else: result = addNodes(n.sons[0]) -proc parseDotDot(p: var TRstParser): PRstNode -proc parseLiteralBlock(p: var TRstParser): PRstNode = +proc parseDotDot(p: var TRstParser): PRSTNode +proc parseLiteralBlock(p: var TRstParser): PRSTNode = result = newRstNode(rnLiteralBlock) var n = newRstNode(rnLeaf, "") if p.tok[p.idx].kind == tkIndent: @@ -953,7 +953,7 @@ proc parseLiteralBlock(p: var TRstParser): PRstNode = inc(p.idx) add(result, n) -proc getLevel(map: var TLevelMap, lvl: var int, c: Char): int = +proc getLevel(map: var TLevelMap, lvl: var int, c: char): int = if map[c] == 0: inc(lvl) map[c] = lvl @@ -999,7 +999,7 @@ proc whichSection(p: TRstParser): TRstNodeKind = elif match(p, p.idx + 1, "i"): result = rnOverline else: result = rnLeaf of tkPunct: - if match(p, tokenAfterNewLine(p), "ai"): + if match(p, tokenAfterNewline(p), "ai"): result = rnHeadline elif p.tok[p.idx].symbol == "::": result = rnLiteralBlock @@ -1026,13 +1026,13 @@ proc whichSection(p: TRstParser): TRstNodeKind = else: result = rnParagraph of tkWord, tkOther, tkWhite: - if match(p, tokenAfterNewLine(p), "ai"): result = rnHeadline + if match(p, tokenAfterNewline(p), "ai"): result = rnHeadline elif match(p, p.idx, "e) ") or match(p, p.idx, "e. "): result = rnEnumList elif isDefList(p): result = rnDefList else: result = rnParagraph else: result = rnLeaf -proc parseLineBlock(p: var TRstParser): PRstNode = +proc parseLineBlock(p: var TRstParser): PRSTNode = result = nil if p.tok[p.idx + 1].kind == tkWhite: var col = p.tok[p.idx].col @@ -1051,7 +1051,7 @@ proc parseLineBlock(p: var TRstParser): PRstNode = break popInd(p) -proc parseParagraph(p: var TRstParser, result: PRstNode) = +proc parseParagraph(p: var TRstParser, result: PRSTNode) = while True: case p.tok[p.idx].kind of tkIndent: @@ -1082,9 +1082,9 @@ proc parseParagraph(p: var TRstParser, result: PRstNode) = parseInline(p, result) else: break -proc parseHeadline(p: var TRstParser): PRstNode = +proc parseHeadline(p: var TRstParser): PRSTNode = result = newRstNode(rnHeadline) - parseUntilNewLine(p, result) + parseUntilNewline(p, result) assert(p.tok[p.idx].kind == tkIndent) assert(p.tok[p.idx + 1].kind == tkAdornment) var c = p.tok[p.idx + 1].symbol[0] @@ -1101,7 +1101,7 @@ proc getColumns(p: var TRstParser, cols: var TIntSeq) = var L = 0 while true: inc(L) - setlen(cols, L) + setLen(cols, L) cols[L - 1] = tokEnd(p) assert(p.tok[p.idx].kind == tkAdornment) inc(p.idx) @@ -1112,16 +1112,16 @@ proc getColumns(p: var TRstParser, cols: var TIntSeq) = # last column has no limit: cols[L - 1] = 32000 -proc parseDoc(p: var TRstParser): PRstNode +proc parseDoc(p: var TRstParser): PRSTNode -proc parseSimpleTable(p: var TRstParser): PRstNode = +proc parseSimpleTable(p: var TRstParser): PRSTNode = var cols: TIntSeq row: seq[string] i, last, line: int - c: Char + c: char q: TRstParser - a, b: PRstNode + a, b: PRSTNode result = newRstNode(rnTable) cols = @[] row = @[] @@ -1135,7 +1135,7 @@ proc parseSimpleTable(p: var TRstParser): PRstNode = p.idx = last break getColumns(p, cols) - setlen(row, len(cols)) + setLen(row, len(cols)) if a != nil: for j in 0..len(a)-1: a.sons[j].kind = rnTableHeaderCell if p.tok[p.idx].kind == tkEof: break @@ -1167,13 +1167,13 @@ proc parseSimpleTable(p: var TRstParser): PRstNode = add(a, b) add(result, a) -proc parseTransition(p: var TRstParser): PRstNode = +proc parseTransition(p: var TRstParser): PRSTNode = result = newRstNode(rnTransition) inc(p.idx) if p.tok[p.idx].kind == tkIndent: inc(p.idx) if p.tok[p.idx].kind == tkIndent: inc(p.idx) -proc parseOverline(p: var TRstParser): PRstNode = +proc parseOverline(p: var TRstParser): PRSTNode = var c = p.tok[p.idx].symbol[0] inc(p.idx, 2) result = newRstNode(rnOverline) @@ -1192,7 +1192,7 @@ proc parseOverline(p: var TRstParser): PRstNode = inc(p.idx) # XXX: check? if p.tok[p.idx].kind == tkIndent: inc(p.idx) -proc parseBulletList(p: var TRstParser): PRstNode = +proc parseBulletList(p: var TRstParser): PRSTNode = result = nil if p.tok[p.idx + 1].kind == tkWhite: var bullet = p.tok[p.idx].symbol @@ -1212,7 +1212,7 @@ proc parseBulletList(p: var TRstParser): PRstNode = break popInd(p) -proc parseOptionList(p: var TRstParser): PRstNode = +proc parseOptionList(p: var TRstParser): PRSTNode = result = newRstNode(rnOptionList) while true: if isOptionList(p): @@ -1241,9 +1241,9 @@ proc parseOptionList(p: var TRstParser): PRstNode = else: break -proc parseDefinitionList(p: var TRstParser): PRstNode = +proc parseDefinitionList(p: var TRstParser): PRSTNode = result = nil - var j = tokenAfterNewLine(p) - 1 + var j = tokenAfterNewline(p) - 1 if (j >= 1) and (p.tok[j].kind == tkIndent) and (p.tok[j].ival > currInd(p)) and (p.tok[j - 1].symbol != "::"): var col = p.tok[p.idx].col @@ -1269,7 +1269,7 @@ proc parseDefinitionList(p: var TRstParser): PRstNode = break if (p.tok[p.idx].kind == tkIndent) and (p.tok[p.idx].ival == col): inc(p.idx) - j = tokenAfterNewLine(p) - 1 + j = tokenAfterNewline(p) - 1 if j >= 1 and p.tok[j].kind == tkIndent and p.tok[j].ival > col and p.tok[j-1].symbol != "::" and p.tok[j+1].kind != tkIndent: nil @@ -1277,7 +1277,7 @@ proc parseDefinitionList(p: var TRstParser): PRstNode = break if len(result) == 0: result = nil -proc parseEnumList(p: var TRstParser): PRstNode = +proc parseEnumList(p: var TRstParser): PRSTNode = const wildcards: array[0..2, string] = ["(e) ", "e) ", "e. "] wildpos: array[0..2, int] = [1, 0, 0] @@ -1290,7 +1290,7 @@ proc parseEnumList(p: var TRstParser): PRstNode = var col = p.tok[p.idx].col result = newRstNode(rnEnumList) inc(p.idx, wildpos[w] + 3) - var j = tokenAfterNewLine(p) + var j = tokenAfterNewline(p) if (p.tok[j].col == p.tok[p.idx].col) or match(p, j, wildcards[w]): pushInd(p, p.tok[p.idx].col) while true: @@ -1307,7 +1307,7 @@ proc parseEnumList(p: var TRstParser): PRstNode = dec(p.idx, wildpos[w] + 3) result = nil -proc sonKind(father: PRstNode, i: int): TRstNodeKind = +proc sonKind(father: PRSTNode, i: int): TRstNodeKind = result = rnLeaf if i < len(father): result = father.sons[i].kind @@ -1328,7 +1328,7 @@ proc parseSection(p: var TRstParser, result: PRstNode) = leave = true break if leave or p.tok[p.idx].kind == tkEof: break - var a: PRstNode = nil + var a: PRSTNode = nil var k = whichSection(p) case k of rnLiteralBlock: @@ -1359,7 +1359,7 @@ proc parseSection(p: var TRstParser, result: PRstNode) = if sonKind(result, 0) == rnParagraph and sonKind(result, 1) != rnParagraph: result.sons[0].kind = rnInner -proc parseSectionWrapper(p: var TRstParser): PRstNode = +proc parseSectionWrapper(p: var TRstParser): PRSTNode = result = newRstNode(rnInner) parseSection(p, result) while (result.kind == rnInner) and (len(result) == 1): @@ -1385,12 +1385,12 @@ type TDirFlag = enum hasArg, hasOptions, argIsFile, argIsWord TDirFlags = set[TDirFlag] - TSectionParser = proc (p: var TRstParser): PRstNode {.nimcall.} + TSectionParser = proc (p: var TRstParser): PRSTNode {.nimcall.} -proc parseDirective(p: var TRstParser, flags: TDirFlags): PRstNode = +proc parseDirective(p: var TRstParser, flags: TDirFlags): PRSTNode = result = newRstNode(rnDirective) - var args: PRstNode = nil - var options: PRstNode = nil + var args: PRSTNode = nil + var options: PRSTNode = nil if hasArg in flags: args = newRstNode(rnDirArg) if argIsFile in flags: @@ -1420,7 +1420,7 @@ proc indFollows(p: TRstParser): bool = result = p.tok[p.idx].kind == tkIndent and p.tok[p.idx].ival > currInd(p) proc parseDirective(p: var TRstParser, flags: TDirFlags, - contentParser: TSectionParser): PRstNode = + contentParser: TSectionParser): PRSTNode = result = parseDirective(p, flags) if not isNil(contentParser) and indFollows(p): pushInd(p, p.tok[p.idx].ival) @@ -1430,13 +1430,13 @@ proc parseDirective(p: var TRstParser, flags: TDirFlags, else: add(result, nil) -proc parseDirBody(p: var TRstParser, contentParser: TSectionParser): PRstNode = +proc parseDirBody(p: var TRstParser, contentParser: TSectionParser): PRSTNode = if indFollows(p): pushInd(p, p.tok[p.idx].ival) result = contentParser(p) popInd(p) -proc dirInclude(p: var TRstParser): PRstNode = +proc dirInclude(p: var TRstParser): PRSTNode = # #The following options are recognized: # @@ -1474,7 +1474,7 @@ proc dirInclude(p: var TRstParser): PRstNode = # InternalError("Too many binary zeros in include file") result = parseDoc(q) -proc dirCodeBlock(p: var TRstParser): PRstNode = +proc dirCodeBlock(p: var TRstParser): PRSTNode = result = parseDirective(p, {hasArg, hasOptions}, parseLiteralBlock) var filename = strip(getFieldValue(result, "file")) if filename != "": @@ -1485,34 +1485,34 @@ proc dirCodeBlock(p: var TRstParser): PRstNode = result.sons[2] = n result.kind = rnCodeBlock -proc dirContainer(p: var TRstParser): PRstNode = +proc dirContainer(p: var TRstParser): PRSTNode = result = parseDirective(p, {hasArg}, parseSectionWrapper) assert(result.kind == rnDirective) assert(len(result) == 3) result.kind = rnContainer -proc dirImage(p: var TRstParser): PRstNode = +proc dirImage(p: var TRstParser): PRSTNode = result = parseDirective(p, {hasOptions, hasArg, argIsFile}, nil) result.kind = rnImage -proc dirFigure(p: var TRstParser): PRstNode = +proc dirFigure(p: var TRstParser): PRSTNode = result = parseDirective(p, {hasOptions, hasArg, argIsFile}, parseSectionWrapper) result.kind = rnFigure -proc dirTitle(p: var TRstParser): PRstNode = +proc dirTitle(p: var TRstParser): PRSTNode = result = parseDirective(p, {hasArg}, nil) result.kind = rnTitle -proc dirContents(p: var TRstParser): PRstNode = +proc dirContents(p: var TRstParser): PRSTNode = result = parseDirective(p, {hasArg}, nil) result.kind = rnContents -proc dirIndex(p: var TRstParser): PRstNode = +proc dirIndex(p: var TRstParser): PRSTNode = result = parseDirective(p, {}, parseSectionWrapper) result.kind = rnIndex -proc dirRawAux(p: var TRstParser, result: var PRstNode, kind: TRstNodeKind, +proc dirRawAux(p: var TRstParser, result: var PRSTNode, kind: TRstNodeKind, contentParser: TSectionParser) = var filename = getFieldValue(result, "file") if filename.len > 0: @@ -1527,7 +1527,7 @@ proc dirRawAux(p: var TRstParser, result: var PRstNode, kind: TRstNodeKind, result.kind = kind add(result, parseDirBody(p, contentParser)) -proc dirRaw(p: var TRstParser): PRstNode = +proc dirRaw(p: var TRstParser): PRSTNode = # #The following options are recognized: # @@ -1581,7 +1581,7 @@ proc parseDotDot(p: var TRstParser): PRstNode = # substitution definitions: inc(p.idx, 2) var a = getReferenceName(p, "|") - var b: PRstNode + var b: PRSTNode if p.tok[p.idx].kind == tkWhite: inc(p.idx) if cmpIgnoreStyle(p.tok[p.idx].symbol, "replace") == 0: inc(p.idx) @@ -1603,7 +1603,7 @@ proc parseDotDot(p: var TRstParser): PRstNode = else: result = parseComment(p) -proc resolveSubs(p: var TRstParser, n: PRstNode): PRstNode = +proc resolveSubs(p: var TRstParser, n: PRSTNode): PRSTNode = result = n if n == nil: return case n.kind @@ -1634,7 +1634,7 @@ proc rstParse*(text, filename: string, line, column: int, hasToc: var bool, options: TRstParseOptions, findFile: TFindFileHandler = nil, - msgHandler: TMsgHandler = nil): PRstNode = + msgHandler: TMsgHandler = nil): PRSTNode = var p: TRstParser initParser(p, newSharedState(options, findFile, msgHandler)) p.filename = filename diff --git a/lib/packages/docutils/rstast.nim b/lib/packages/docutils/rstast.nim index c2ff53b58..bb0b61889 100644 --- a/lib/packages/docutils/rstast.nim +++ b/lib/packages/docutils/rstast.nim @@ -62,8 +62,8 @@ type # leaf val - PRSTNode* = ref TRstNode ## an RST node - TRstNodeSeq* = seq[PRstNode] + PRSTNode* = ref TRSTNode ## an RST node + TRstNodeSeq* = seq[PRSTNode] TRSTNode* {.acyclic, final.} = object ## an RST node's description kind*: TRstNodeKind ## the node's kind text*: string ## valid for leafs in the AST; and the title of @@ -71,25 +71,25 @@ type level*: int ## valid for some node kinds sons*: TRstNodeSeq ## the node's sons -proc len*(n: PRstNode): int = +proc len*(n: PRSTNode): int = result = len(n.sons) -proc newRstNode*(kind: TRstNodeKind): PRstNode = +proc newRstNode*(kind: TRstNodeKind): PRSTNode = new(result) result.sons = @[] result.kind = kind -proc newRstNode*(kind: TRstNodeKind, s: string): PRstNode = +proc newRstNode*(kind: TRstNodeKind, s: string): PRSTNode = result = newRstNode(kind) result.text = s -proc lastSon*(n: PRstNode): PRstNode = +proc lastSon*(n: PRSTNode): PRSTNode = result = n.sons[len(n.sons)-1] -proc add*(father, son: PRstNode) = +proc add*(father, son: PRSTNode) = add(father.sons, son) -proc addIfNotNil*(father, son: PRstNode) = +proc addIfNotNil*(father, son: PRSTNode) = if son != nil: add(father, son) @@ -98,9 +98,9 @@ type indent: int verbatim: int -proc renderRstToRst(d: var TRenderContext, n: PRstNode, result: var string) +proc renderRstToRst(d: var TRenderContext, n: PRSTNode, result: var string) -proc renderRstSons(d: var TRenderContext, n: PRstNode, result: var string) = +proc renderRstSons(d: var TRenderContext, n: PRSTNode, result: var string) = for i in countup(0, len(n) - 1): renderRstToRst(d, n.sons[i], result) @@ -132,7 +132,7 @@ proc renderRstToRst(d: var TRenderContext, n: PRstNode, result: var string) = var headline = "" renderRstSons(d, n, headline) - let lvl = repeatChar(headline.Len - d.indent, lvlToChar[n.level]) + let lvl = repeatChar(headline.len - d.indent, lvlToChar[n.level]) result.add(lvl) result.add("\n") result.add(headline) @@ -281,7 +281,7 @@ proc renderRstToRst(d: var TRenderContext, n: PRstNode, result: var string) = else: result.add("Error: cannot render: " & $n.kind) -proc renderRstToRst*(n: PRstNode, result: var string) = +proc renderRstToRst*(n: PRSTNode, result: var string) = ## renders `n` into its string representation and appends to `result`. var d: TRenderContext renderRstToRst(d, n, result) diff --git a/lib/packages/docutils/rstgen.nim b/lib/packages/docutils/rstgen.nim index 157e04d5b..f43c6e478 100644 --- a/lib/packages/docutils/rstgen.nim +++ b/lib/packages/docutils/rstgen.nim @@ -32,7 +32,7 @@ type outLatex # output is Latex TTocEntry{.final.} = object - n*: PRstNode + n*: PRSTNode refname*, header*: string TMetaEnum* = enum @@ -113,7 +113,7 @@ proc initRstGenerator*(g: var TRstGenerator, target: TOutputTarget, proc writeIndexFile*(g: var TRstGenerator, outfile: string) = if g.theIndex.len > 0: writeFile(outfile, g.theIndex) -proc addXmlChar(dest: var string, c: Char) = +proc addXmlChar(dest: var string, c: char) = case c of '&': add(dest, "&") of '<': add(dest, "<") @@ -121,14 +121,14 @@ proc addXmlChar(dest: var string, c: Char) = of '\"': add(dest, """) else: add(dest, c) -proc addRtfChar(dest: var string, c: Char) = +proc addRtfChar(dest: var string, c: char) = case c of '{': add(dest, "\\{") of '}': add(dest, "\\}") of '\\': add(dest, "\\\\") else: add(dest, c) -proc addTexChar(dest: var string, c: Char) = +proc addTexChar(dest: var string, c: char) = case c of '_': add(dest, "\\_") of '{': add(dest, "\\symbol{123}") @@ -148,7 +148,7 @@ proc addTexChar(dest: var string, c: Char) = var splitter*: string = "<wbr />" -proc escChar*(target: TOutputTarget, dest: var string, c: Char) {.inline.} = +proc escChar*(target: TOutputTarget, dest: var string, c: char) {.inline.} = case target of outHtml: addXmlChar(dest, c) of outLatex: addTexChar(dest, c) @@ -196,7 +196,7 @@ proc dispA(target: TOutputTarget, dest: var string, if target != outLatex: addf(dest, xml, args) else: addf(dest, tex, args) -proc renderRstToOut*(d: var TRstGenerator, n: PRstNode, result: var string) +proc renderRstToOut*(d: var TRstGenerator, n: PRSTNode, result: var string) ## Writes into ``result`` the rst ast ``n`` using the ``d`` configuration. ## ## Before using this proc you need to initialise a ``TRstGenerator`` with @@ -210,10 +210,10 @@ proc renderRstToOut*(d: var TRstGenerator, n: PRstNode, result: var string) ## renderRstToOut(gen, rst, generatedHTML) ## echo generatedHTML -proc renderAux(d: PDoc, n: PRstNode, result: var string) = +proc renderAux(d: PDoc, n: PRSTNode, result: var string) = for i in countup(0, len(n)-1): renderRstToOut(d, n.sons[i], result) -proc renderAux(d: PDoc, n: PRstNode, frmtA, frmtB: string, result: var string) = +proc renderAux(d: PDoc, n: PRSTNode, frmtA, frmtB: string, result: var string) = var tmp = "" for i in countup(0, len(n)-1): renderRstToOut(d, n.sons[i], tmp) if d.target != outLatex: @@ -232,7 +232,7 @@ proc setIndexTerm*(d: var TRstGenerator, id, term: string) = d.theIndex.add(id) d.theIndex.add("\n") -proc hash(n: PRstNode): int = +proc hash(n: PRSTNode): int = if n.kind == rnLeaf: result = hash(n.text) elif n.len > 0: @@ -241,7 +241,7 @@ proc hash(n: PRstNode): int = result = result !& hash(n.sons[i]) result = !$result -proc renderIndexTerm(d: PDoc, n: PRstNode, result: var string) = +proc renderIndexTerm(d: PDoc, n: PRSTNode, result: var string) = let id = rstnodeToRefname(n) & '_' & $abs(hash(n)) var term = "" renderAux(d, n, term) @@ -314,13 +314,13 @@ proc mergeIndexes*(dir: string): string = # ---------------------------------------------------------------------------- -proc renderHeadline(d: PDoc, n: PRstNode, result: var string) = +proc renderHeadline(d: PDoc, n: PRSTNode, result: var string) = var tmp = "" for i in countup(0, len(n) - 1): renderRstToOut(d, n.sons[i], tmp) var refname = rstnodeToRefname(n) if d.hasToc: var length = len(d.tocPart) - setlen(d.tocPart, length + 1) + setLen(d.tocPart, length + 1) d.tocPart[length].refname = refname d.tocPart[length].n = n d.tocPart[length].header = tmp @@ -336,7 +336,7 @@ proc renderHeadline(d: PDoc, n: PRstNode, result: var string) = $n.level, refname, tmp, $chr(n.level - 1 + ord('A'))]) -proc renderOverline(d: PDoc, n: PRstNode, result: var string) = +proc renderOverline(d: PDoc, n: PRSTNode, result: var string) = if d.meta[metaTitle].len == 0: for i in countup(0, len(n)-1): renderRstToOut(d, n.sons[i], d.meta[metaTitle]) @@ -373,7 +373,7 @@ proc renderTocEntries*(d: var TRstGenerator, j: var int, lvl: int, result: var s else: result.add(tmp) -proc renderImage(d: PDoc, n: PRstNode, result: var string) = +proc renderImage(d: PDoc, n: PRSTNode, result: var string) = var options = "" var s = getFieldValue(n, "scale") if s != "": dispA(d.target, options, " scale=\"$1\"", " scale=$1", [strip(s)]) @@ -396,13 +396,13 @@ proc renderImage(d: PDoc, n: PRstNode, result: var string) = [getArgument(n), options]) if len(n) >= 3: renderRstToOut(d, n.sons[2], result) -proc renderSmiley(d: PDoc, n: PRstNode, result: var string) = +proc renderSmiley(d: PDoc, n: PRSTNode, result: var string) = dispA(d.target, result, """<img src="/images/smilies/$1.gif" width="15" height="17" hspace="2" vspace="2" />""", "\\includegraphics{$1}", [n.text]) -proc renderCodeBlock(d: PDoc, n: PRstNode, result: var string) = +proc renderCodeBlock(d: PDoc, n: PRSTNode, result: var string) = if n.sons[2] == nil: return var m = n.sons[2].sons[0] assert m.kind == rnLeaf @@ -433,7 +433,7 @@ proc renderCodeBlock(d: PDoc, n: PRstNode, result: var string) = deinitGeneralTokenizer(g) dispA(d.target, result, "</pre>", "\n\\end{rstpre}\n") -proc renderContainer(d: PDoc, n: PRstNode, result: var string) = +proc renderContainer(d: PDoc, n: PRSTNode, result: var string) = var tmp = "" renderRstToOut(d, n.sons[2], tmp) var arg = strip(getArgument(n)) @@ -442,11 +442,11 @@ proc renderContainer(d: PDoc, n: PRstNode, result: var string) = else: dispA(d.target, result, "<div class=\"$1\">$2</div>", "$2", [arg, tmp]) -proc texColumns(n: PRstNode): string = +proc texColumns(n: PRSTNode): string = result = "" for i in countup(1, len(n)): add(result, "|X") -proc renderField(d: PDoc, n: PRstNode, result: var string) = +proc renderField(d: PDoc, n: PRSTNode, result: var string) = var b = false if d.target == outLatex: var fieldname = addNodes(n.sons[0]) @@ -456,7 +456,7 @@ proc renderField(d: PDoc, n: PRstNode, result: var string) = if d.meta[metaAuthor].len == 0: d.meta[metaAuthor] = fieldval b = true - elif cmpIgnoreStyle(fieldName, "version") == 0: + elif cmpIgnoreStyle(fieldname, "version") == 0: if d.meta[metaVersion].len == 0: d.meta[metaVersion] = fieldval b = true @@ -620,14 +620,14 @@ proc renderRstToOut(d: PDoc, n: PRstNode, result: var string) = # ----------------------------------------------------------------------------- -proc getVarIdx(varnames: openarray[string], id: string): int = +proc getVarIdx(varnames: openArray[string], id: string): int = for i in countup(0, high(varnames)): if cmpIgnoreStyle(varnames[i], id) == 0: return i result = -1 -proc formatNamedVars*(frmt: string, varnames: openarray[string], - varvalues: openarray[string]): string = +proc formatNamedVars*(frmt: string, varnames: openArray[string], + varvalues: openArray[string]): string = var i = 0 var L = len(frmt) result = "" @@ -646,7 +646,7 @@ proc formatNamedVars*(frmt: string, varnames: openarray[string], of '0'..'9': var j = 0 while true: - j = (j * 10) + Ord(frmt[i]) - ord('0') + j = (j * 10) + ord(frmt[i]) - ord('0') inc(i) if i > L-1 or frmt[i] notin {'0'..'9'}: break if j > high(varvalues) + 1: diff --git a/lib/pure/algorithm.nim b/lib/pure/algorithm.nim index 8b44e69d9..df7ae6d17 100644 --- a/lib/pure/algorithm.nim +++ b/lib/pure/algorithm.nim @@ -34,7 +34,7 @@ proc reverse*[T](a: var openArray[T]) = ## reverses the array `a`. reverse(a, 0, a.high) -proc binarySearch*[T](a: openarray[T], key: T): int = +proc binarySearch*[T](a: openArray[T], key: T): int = ## binary search for `key` in `a`. Returns -1 if not found. var b = len(a) while result < b: @@ -79,7 +79,7 @@ proc merge[T](a, b: var openArray[T], lo, m, hi: int, inc(bb) inc(j) else: - CopyMem(addr(b[0]), addr(a[j]), sizeof(T)*(m-j+1)) + copyMem(addr(b[0]), addr(a[j]), sizeof(T)*(m-j+1)) j = m+1 var i = 0 var k = lo diff --git a/lib/pure/collections/intsets.nim b/lib/pure/collections/intsets.nim index 367caf2e7..f1e67fc0e 100644 --- a/lib/pure/collections/intsets.nim +++ b/lib/pure/collections/intsets.nim @@ -71,8 +71,8 @@ proc intSetEnlarge(t: var TIntSet) = var oldMax = t.max t.max = ((t.max + 1) * 2) - 1 newSeq(n, t.max + 1) - for i in countup(0, oldmax): - if t.data[i] != nil: IntSetRawInsert(t, n, t.data[i]) + for i in countup(0, oldMax): + if t.data[i] != nil: intSetRawInsert(t, n, t.data[i]) swap(t.data, n) proc intSetPut(t: var TIntSet, key: int): PTrunk = @@ -81,7 +81,7 @@ proc intSetPut(t: var TIntSet, key: int): PTrunk = if t.data[h].key == key: return t.data[h] h = nextTry(h, t.max) - if mustRehash(t.max + 1, t.counter): IntSetEnlarge(t) + if mustRehash(t.max + 1, t.counter): intSetEnlarge(t) inc(t.counter) h = key and t.max while t.data[h] != nil: h = nextTry(h, t.max) @@ -94,7 +94,7 @@ proc intSetPut(t: var TIntSet, key: int): PTrunk = proc contains*(s: TIntSet, key: int): bool = ## returns true iff `key` is in `s`. - var t = IntSetGet(s, `shr`(key, TrunkShift)) + var t = intSetGet(s, `shr`(key, TrunkShift)) if t != nil: var u = key and TrunkMask result = (t.bits[`shr`(u, IntShift)] and `shl`(1, u and IntMask)) != 0 @@ -103,14 +103,14 @@ proc contains*(s: TIntSet, key: int): bool = proc incl*(s: var TIntSet, key: int) = ## includes an element `key` in `s`. - var t = IntSetPut(s, `shr`(key, TrunkShift)) + var t = intSetPut(s, `shr`(key, TrunkShift)) var u = key and TrunkMask t.bits[`shr`(u, IntShift)] = t.bits[`shr`(u, IntShift)] or `shl`(1, u and IntMask) proc excl*(s: var TIntSet, key: int) = ## excludes `key` from the set `s`. - var t = IntSetGet(s, `shr`(key, TrunkShift)) + var t = intSetGet(s, `shr`(key, TrunkShift)) if t != nil: var u = key and TrunkMask t.bits[`shr`(u, IntShift)] = t.bits[`shr`(u, IntShift)] and @@ -119,7 +119,7 @@ proc excl*(s: var TIntSet, key: int) = proc containsOrIncl*(s: var TIntSet, key: int): bool = ## returns true if `s` contains `key`, otherwise `key` is included in `s` ## and false is returned. - var t = IntSetGet(s, `shr`(key, TrunkShift)) + var t = intSetGet(s, `shr`(key, TrunkShift)) if t != nil: var u = key and TrunkMask result = (t.bits[`shr`(u, IntShift)] and `shl`(1, u and IntMask)) != 0 diff --git a/lib/pure/collections/sequtils.nim b/lib/pure/collections/sequtils.nim index 3a009a8cb..3993f1ccc 100644 --- a/lib/pure/collections/sequtils.nim +++ b/lib/pure/collections/sequtils.nim @@ -136,7 +136,7 @@ proc delete*[T](s: var seq[T], first=0, last=0) = s[i].shallowCopy(s[j]) inc(i) inc(j) - setlen(s, newLen) + setLen(s, newLen) proc insert*[T](dest: var seq[T], src: openArray[T], pos=0) = ## Inserts items from `src` into `dest` at position `pos`. This modifies diff --git a/lib/pure/collections/tables.nim b/lib/pure/collections/tables.nim index ef3a529a1..4b9e8af0e 100644 --- a/lib/pure/collections/tables.nim +++ b/lib/pure/collections/tables.nim @@ -168,7 +168,7 @@ proc initTable*[A, B](initialSize=64): TTable[A, B] = result.counter = 0 newSeq(result.data, initialSize) -proc toTable*[A, B](pairs: openarray[tuple[key: A, +proc toTable*[A, B](pairs: openArray[tuple[key: A, val: B]]): TTable[A, B] = ## creates a new hash table that contains the given `pairs`. result = initTable[A, B](nextPowerOfTwo(pairs.len+10)) @@ -304,7 +304,7 @@ proc initOrderedTable*[A, B](initialSize=64): TOrderedTable[A, B] = result.last = -1 newSeq(result.data, initialSize) -proc toOrderedTable*[A, B](pairs: openarray[tuple[key: A, +proc toOrderedTable*[A, B](pairs: openArray[tuple[key: A, val: B]]): TOrderedTable[A, B] = ## creates a new ordered hash table that contains the given `pairs`. result = initOrderedTable[A, B](nextPowerOfTwo(pairs.len+10)) @@ -463,7 +463,7 @@ proc `$`*[A](t: TCountTable[A]): string = proc inc*[A](t: var TCountTable[A], key: A, val = 1) = ## increments `t[key]` by `val`. - var index = RawGet(t, key) + var index = rawGet(t, key) if index >= 0: inc(t.data[index].val, val) else: diff --git a/lib/pure/hashes.nim b/lib/pure/hashes.nim index 8a3135f89..1c0c59a7c 100644 --- a/lib/pure/hashes.nim +++ b/lib/pure/hashes.nim @@ -32,7 +32,7 @@ proc `!$`*(h: THash): THash {.inline.} = result = result xor (result shr 11) result = result +% result shl 15 -proc hashData*(Data: Pointer, Size: int): THash = +proc hashData*(Data: pointer, Size: int): THash = ## hashes an array of bytes of size `size` var h: THash = 0 when defined(js): @@ -41,17 +41,17 @@ proc hashData*(Data: Pointer, Size: int): THash = else: var p = cast[cstring](Data) var i = 0 - var s = size + var s = Size while s > 0: h = h !& ord(p[i]) - Inc(i) - Dec(s) + inc(i) + dec(s) result = !$h when defined(js): var objectID = 0 -proc hash*(x: Pointer): THash {.inline.} = +proc hash*(x: pointer): THash {.inline.} = ## efficient hashing of pointers when defined(js): asm """ @@ -126,6 +126,6 @@ proc hash*(x: float): THash {.inline.} = var y = x + 1.0 result = cast[ptr THash](addr(y))[] -proc hash*[A](x: openarray[A]): THash = +proc hash*[A](x: openArray[A]): THash = for it in items(x): result = result !& hash(it) result = !$result diff --git a/lib/pure/json.nim b/lib/pure/json.nim index df20bd852..f0d0aa0c0 100644 --- a/lib/pure/json.nim +++ b/lib/pure/json.nim @@ -135,7 +135,7 @@ proc str*(my: TJsonParser): string {.inline.} = assert(my.kind in {jsonInt, jsonFloat, jsonString}) return my.a -proc getInt*(my: TJsonParser): biggestInt {.inline.} = +proc getInt*(my: TJsonParser): BiggestInt {.inline.} = ## returns the number for the event: ``jsonInt`` assert(my.kind == jsonInt) return parseBiggestInt(my.a) @@ -173,7 +173,7 @@ proc errorMsgExpected*(my: TJsonParser, e: string): string = result = "$1($2, $3) Error: $4" % [ my.filename, $getLine(my), $getColumn(my), e & " expected"] -proc handleHexChar(c: Char, x: var int): bool = +proc handleHexChar(c: char, x: var int): bool = result = true # Success case c of '0'..'9': x = (x shl 4) or (ord(c) - ord('0')) @@ -286,7 +286,7 @@ proc skip(my: var TJsonParser) = else: break of ' ', '\t': - Inc(pos) + inc(pos) of '\c': pos = lexbase.HandleCR(my, pos) buf = my.buf @@ -517,7 +517,7 @@ type of JString: str*: string of JInt: - num*: biggestInt + num*: BiggestInt of JFloat: fnum*: float of JBool: @@ -535,30 +535,30 @@ proc raiseParseErr*(p: TJsonParser, msg: string) {.noinline, noreturn.} = ## raises an `EJsonParsingError` exception. raise newException(EJsonParsingError, errorMsgExpected(p, msg)) -proc newJString*(s: String): PJsonNode = +proc newJString*(s: string): PJsonNode = ## Creates a new `JString PJsonNode`. new(result) result.kind = JString result.str = s -proc newJStringMove(s: String): PJsonNode = +proc newJStringMove(s: string): PJsonNode = new(result) result.kind = JString shallowCopy(result.str, s) -proc newJInt*(n: biggestInt): PJsonNode = +proc newJInt*(n: BiggestInt): PJsonNode = ## Creates a new `JInt PJsonNode`. new(result) result.kind = JInt result.num = n -proc newJFloat*(n: Float): PJsonNode = +proc newJFloat*(n: float): PJsonNode = ## Creates a new `JFloat PJsonNode`. new(result) result.kind = JFloat result.fnum = n -proc newJBool*(b: Bool): PJsonNode = +proc newJBool*(b: bool): PJsonNode = ## Creates a new `JBool PJsonNode`. new(result) result.kind = JBool @@ -587,7 +587,7 @@ proc `%`*(s: string): PJsonNode = result.kind = JString result.str = s -proc `%`*(n: biggestInt): PJsonNode = +proc `%`*(n: BiggestInt): PJsonNode = ## Generic constructor for JSON data. Creates a new `JInt PJsonNode`. new(result) result.kind = JInt @@ -612,7 +612,7 @@ proc `%`*(keyVals: openArray[tuple[key: string, val: PJsonNode]]): PJsonNode = newSeq(result.fields, keyVals.len) for i, p in pairs(keyVals): result.fields[i] = p -proc `%`*(elements: openArray[PJSonNode]): PJsonNode = +proc `%`*(elements: openArray[PJsonNode]): PJsonNode = ## Generic constructor for JSON data. Creates a new `JArray PJsonNode` new(result) result.kind = JArray @@ -628,7 +628,7 @@ proc len*(n: PJsonNode): int = of JObject: result = n.fields.len else: nil -proc `[]`*(node: PJsonNode, name: String): PJsonNode = +proc `[]`*(node: PJsonNode, name: string): PJsonNode = ## Gets a field from a `JObject`. Returns nil if the key is not found. assert(node.kind == JObject) for key, item in items(node.fields): @@ -636,17 +636,17 @@ proc `[]`*(node: PJsonNode, name: String): PJsonNode = return item return nil -proc `[]`*(node: PJsonNode, index: Int): PJsonNode = +proc `[]`*(node: PJsonNode, index: int): PJsonNode = ## Gets the node at `index` in an Array. assert(node.kind == JArray) return node.elems[index] -proc hasKey*(node: PJsonNode, key: String): Bool = +proc hasKey*(node: PJsonNode, key: string): bool = ## Checks if `key` exists in `node`. assert(node.kind == JObject) for k, item in items(node.fields): if k == key: return True -proc existsKey*(node: PJsonNode, key: String): Bool {.deprecated.} = node.hasKey(key) +proc existsKey*(node: PJsonNode, key: string): bool {.deprecated.} = node.hasKey(key) ## Deprecated for `hasKey` proc add*(father, child: PJsonNode) = @@ -661,7 +661,7 @@ proc add*(obj: PJsonNode, key: string, val: PJsonNode) = assert obj.kind == JObject obj.fields.add((key, val)) -proc `[]=`*(obj: PJsonNode, key: String, val: PJsonNode) = +proc `[]=`*(obj: PJsonNode, key: string, val: PJsonNode) = ## Sets a field from a `JObject`. Performs a check for duplicate keys. assert(obj.kind == JObject) for i in 0..obj.fields.len-1: @@ -706,7 +706,7 @@ proc copy*(p: PJsonNode): PJsonNode = proc indent(s: var string, i: int) = s.add(repeatChar(i)) -proc newIndent(curr, indent: int, ml: bool): Int = +proc newIndent(curr, indent: int, ml: bool): int = if ml: return curr + indent else: return indent @@ -785,18 +785,18 @@ proc toPretty(result: var string, node: PJsonNode, indent = 2, ml = True, if lstArr: result.indent(currIndent) result.add("null") -proc pretty*(node: PJsonNode, indent = 2): String = +proc pretty*(node: PJsonNode, indent = 2): string = ## Converts `node` to its JSON Representation, with indentation and ## on multiple lines. result = "" toPretty(result, node, indent) -proc `$`*(node: PJsonNode): String = +proc `$`*(node: PJsonNode): string = ## Converts `node` to its JSON Representation on one line. result = "" toPretty(result, node, 1, False) -iterator items*(node: PJsonNode): PJSonNode = +iterator items*(node: PJsonNode): PJsonNode = ## Iterator for the items of `node`. `node` has to be a JArray. assert node.kind == JArray for i in items(node.elems): diff --git a/lib/pure/lexbase.nim b/lib/pure/lexbase.nim index 3b3e3810b..243c7dc4a 100644 --- a/lib/pure/lexbase.nim +++ b/lib/pure/lexbase.nim @@ -91,7 +91,7 @@ proc fillBuffer(L: var TBaseLexer) = dec(s) # BUGFIX (valgrind) while true: assert(s < L.bufLen) - while (s >= 0) and not (L.buf[s] in NewLines): Dec(s) + while (s >= 0) and not (L.buf[s] in NewLines): dec(s) if s >= 0: # we found an appropriate character for a sentinel: L.sentinel = s @@ -163,5 +163,5 @@ proc getCurrentLine(L: TBaseLexer, marker: bool = true): string = inc(i) add(result, "\n") if marker: - add(result, RepeatChar(getColNumber(L, L.bufpos)) & "^\n") + add(result, repeatChar(getColNumber(L, L.bufpos)) & "^\n") diff --git a/lib/pure/math.nim b/lib/pure/math.nim index 35b9607e0..062cfae25 100644 --- a/lib/pure/math.nim +++ b/lib/pure/math.nim @@ -94,7 +94,7 @@ proc nextPowerOfTwo*(x: int): int = result = result or (result shr 4) result = result or (result shr 2) result = result or (result shr 1) - Inc(result) + inc(result) proc countBits32*(n: int32): int {.noSideEffect.} = ## counts the set bits in `n`. @@ -103,17 +103,17 @@ proc countBits32*(n: int32): int {.noSideEffect.} = v = (v and 0x33333333'i32) +% ((v shr 2'i32) and 0x33333333'i32) result = ((v +% (v shr 4'i32) and 0xF0F0F0F'i32) *% 0x1010101'i32) shr 24'i32 -proc sum*[T](x: openarray[T]): T {.noSideEffect.} = +proc sum*[T](x: openArray[T]): T {.noSideEffect.} = ## computes the sum of the elements in `x`. ## If `x` is empty, 0 is returned. for i in items(x): result = result + i -proc mean*(x: openarray[float]): float {.noSideEffect.} = +proc mean*(x: openArray[float]): float {.noSideEffect.} = ## computes the mean of the elements in `x`. ## If `x` is empty, NaN is returned. result = sum(x) / toFloat(len(x)) -proc variance*(x: openarray[float]): float {.noSideEffect.} = +proc variance*(x: openArray[float]): float {.noSideEffect.} = ## computes the variance of the elements in `x`. ## If `x` is empty, NaN is returned. result = 0.0 diff --git a/lib/pure/memfiles.nim b/lib/pure/memfiles.nim index 9f4094b40..d8a27fde3 100644 --- a/lib/pure/memfiles.nim +++ b/lib/pure/memfiles.nim @@ -52,9 +52,9 @@ proc open*(filename: string, mode: TFileMode = fmRead, when defined(windows): template fail(errCode: TOSErrorCode, msg: expr) = rollback() - if result.fHandle != 0: discard CloseHandle(result.fHandle) - if result.mapHandle != 0: discard CloseHandle(result.mapHandle) - OSError(errCode) + if result.fHandle != 0: discard closeHandle(result.fHandle) + if result.mapHandle != 0: discard closeHandle(result.mapHandle) + osError(errCode) # return false #raise newException(EIO, msg) @@ -69,36 +69,36 @@ proc open*(filename: string, mode: TFileMode = fmRead, 0) when useWinUnicode: - result.fHandle = callCreateFile(CreateFileW, newWideCString(filename)) + result.fHandle = callCreateFile(createFileW, newWideCString(filename)) else: result.fHandle = callCreateFile(CreateFileA, filename) if result.fHandle == INVALID_HANDLE_VALUE: - fail(OSLastError(), "error opening file") + fail(osLastError(), "error opening file") if newFileSize != -1: var sizeHigh = int32(newFileSize shr 32) sizeLow = int32(newFileSize and 0xffffffff) - var status = SetFilePointer(result.fHandle, sizeLow, addr(sizeHigh), + var status = setFilePointer(result.fHandle, sizeLow, addr(sizeHigh), FILE_BEGIN) - let lastErr = OSLastError() + let lastErr = osLastError() if (status == INVALID_SET_FILE_POINTER and lastErr.int32 != NO_ERROR) or - (SetEndOfFile(result.fHandle) == 0): + (setEndOfFile(result.fHandle) == 0): fail(lastErr, "error setting file size") # since the strings are always 'nil', we simply always call # CreateFileMappingW which should be slightly faster anyway: - result.mapHandle = CreateFileMappingW( + result.mapHandle = createFileMappingW( result.fHandle, nil, if readonly: PAGE_READONLY else: PAGE_READWRITE, 0, 0, nil) if result.mapHandle == 0: - fail(OSLastError(), "error creating mapping") + fail(osLastError(), "error creating mapping") - result.mem = MapViewOfFileEx( + result.mem = mapViewOfFileEx( result.mapHandle, if readonly: FILE_MAP_READ else: FILE_MAP_WRITE, int32(offset shr 32), @@ -107,12 +107,12 @@ proc open*(filename: string, mode: TFileMode = fmRead, nil) if result.mem == nil: - fail(OSLastError(), "error mapping view") + fail(osLastError(), "error mapping view") var hi, low: int32 - low = GetFileSize(result.fHandle, addr(hi)) + low = getFileSize(result.fHandle, addr(hi)) if low == INVALID_FILE_SIZE: - fail(OSLastError(), "error getting file size") + fail(osLastError(), "error getting file size") else: var fileSize = (int64(hi) shr 32) or low if mappedSize != -1: result.size = min(fileSize, mappedSize).int @@ -170,10 +170,10 @@ proc close*(f: var TMemFile) = when defined(windows): if f.fHandle != INVALID_HANDLE_VALUE: - lastErr = OSLastError() - error = UnmapViewOfFile(f.mem) == 0 - error = (CloseHandle(f.mapHandle) == 0) or error - error = (CloseHandle(f.fHandle) == 0) or error + lastErr = osLastError() + error = unmapViewOfFile(f.mem) == 0 + error = (closeHandle(f.mapHandle) == 0) or error + error = (closeHandle(f.fHandle) == 0) or error else: if f.handle != 0: lastErr = OSLastError() @@ -189,5 +189,5 @@ proc close*(f: var TMemFile) = else: f.handle = 0 - if error: OSError(lastErr) + if error: osError(lastErr) diff --git a/lib/pure/os.nim b/lib/pure/os.nim index 761ed4bc4..fbca89f52 100644 --- a/lib/pure/os.nim +++ b/lib/pure/os.nim @@ -189,7 +189,7 @@ proc osErrorMsg*(): string {.rtl, extern: "nos$1", deprecated.} = var err = getLastError() if err != 0'i32: when useWinUnicode: - var msgbuf: widecstring + var msgbuf: WideCString if formatMessageW(0x00000100 or 0x00001000 or 0x00000200, nil, err, 0, addr(msgbuf), 0, nil) != 0'i32: result = $msgbuf @@ -237,7 +237,7 @@ proc osErrorMsg*(errorCode: TOSErrorCode): string = when defined(Windows): if errorCode != TOSErrorCode(0'i32): when useWinUnicode: - var msgbuf: widecstring + var msgbuf: WideCString if formatMessageW(0x00000100 or 0x00001000 or 0x00000200, nil, errorCode.int32, 0, addr(msgbuf), 0, nil) != 0'i32: result = $msgbuf @@ -282,7 +282,7 @@ proc osLastError*(): TOSErrorCode = ## immediately after an OS call fails. On POSIX systems this is not a problem. when defined(windows): - result = TOSErrorCode(GetLastError()) + result = TOSErrorCode(getLastError()) else: result = TOSErrorCode(errno) {.pop.} @@ -394,11 +394,11 @@ proc getLastModificationTime*(file: string): TTime {.rtl, extern: "nos$1".} = if stat(file, res) < 0'i32: osError(osLastError()) return res.st_mtime else: - var f: TWIN32_Find_Data + var f: TWIN32_FIND_DATA var h = findFirstFile(file, f) if h == -1'i32: osError(osLastError()) result = winTimeToUnixTime(rdFileTime(f.ftLastWriteTime)) - findclose(h) + findClose(h) proc getLastAccessTime*(file: string): TTime {.rtl, extern: "nos$1".} = ## Returns the `file`'s last read or write access time. @@ -407,11 +407,11 @@ proc getLastAccessTime*(file: string): TTime {.rtl, extern: "nos$1".} = if stat(file, res) < 0'i32: osError(osLastError()) return res.st_atime else: - var f: TWIN32_Find_Data + var f: TWIN32_FIND_DATA var h = findFirstFile(file, f) if h == -1'i32: osError(osLastError()) result = winTimeToUnixTime(rdFileTime(f.ftLastAccessTime)) - findclose(h) + findClose(h) proc getCreationTime*(file: string): TTime {.rtl, extern: "nos$1".} = ## Returns the `file`'s creation time. @@ -420,11 +420,11 @@ proc getCreationTime*(file: string): TTime {.rtl, extern: "nos$1".} = if stat(file, res) < 0'i32: osError(osLastError()) return res.st_ctime else: - var f: TWIN32_Find_Data + var f: TWIN32_FIND_DATA var h = findFirstFile(file, f) if h == -1'i32: osError(osLastError()) result = winTimeToUnixTime(rdFileTime(f.ftCreationTime)) - findclose(h) + findClose(h) proc fileNewer*(a, b: string): bool {.rtl, extern: "nos$1".} = ## Returns true if the file `a` is newer than file `b`, i.e. if `a`'s @@ -670,7 +670,7 @@ proc expandFilename*(filename: string): string {.rtl, extern: "nos$1", when defined(windows): const bufsize = 3072'i32 when useWinUnicode: - var unused: widecstring + var unused: WideCString var res = newWideCString("", bufsize div 2) var L = getFullPathNameW(newWideCString(filename), bufsize, res, unused) if L <= 0'i32 or L >= bufsize: @@ -957,7 +957,7 @@ proc copyFile*(source, dest: string) {.rtl, extern: "nos$1", proc moveFile*(source, dest: string) {.rtl, extern: "nos$1", tags: [FReadIO, FWriteIO].} = ## Moves a file from `source` to `dest`. If this fails, `EOS` is raised. - if crename(source, dest) != 0'i32: + if c_rename(source, dest) != 0'i32: raise newException(EOS, $strerror(errno)) when not defined(ENOENT) and not defined(Windows): @@ -1005,7 +1005,7 @@ proc execShellCmd*(command: string): int {.rtl, extern: "nos$1", ## the process has finished. To execute a program without having a ## shell involved, use the `execProcess` proc of the `osproc` ## module. - result = csystem(command) + result = c_system(command) # Environment handling cannot be put into RTL, because the ``envPairs`` # iterator depends on ``environment``. @@ -1018,7 +1018,7 @@ when defined(windows): # because we support Windows GUI applications, things get really # messy here... when useWinUnicode: - proc strEnd(cstr: wideCString, c = 0'i32): wideCString {. + proc strEnd(cstr: WideCString, c = 0'i32): WideCString {. importc: "wcschr", header: "<string.h>".} else: proc strEnd(cstr: cstring, c = 0'i32): cstring {. @@ -1035,9 +1035,9 @@ when defined(windows): while True: var eend = strEnd(e) add(environment, $e) - e = cast[wideCString](cast[TAddress](eend)+2) + e = cast[WideCString](cast[TAddress](eend)+2) if eend[1].int == 0: break - discard FreeEnvironmentStringsW(env) + discard freeEnvironmentStringsW(env) else: var env = getEnvironmentStringsA() @@ -1099,14 +1099,14 @@ proc getEnv*(key: string): TaintedString {.tags: [FReadEnv].} = if i >= 0: return TaintedString(substr(environment[i], find(environment[i], '=')+1)) else: - var env = cgetenv(key) + var env = c_getenv(key) if env == nil: return TaintedString("") result = TaintedString($env) proc existsEnv*(key: string): bool {.tags: [FReadEnv].} = ## Checks whether the environment variable named `key` exists. ## Returns true if it exists, false otherwise. - if cgetenv(key) != nil: return true + if c_getenv(key) != nil: return true else: return findEnvVar(key) >= 0 proc putEnv*(key, val: string) {.tags: [FWriteEnv].} = @@ -1152,15 +1152,15 @@ iterator walkFiles*(pattern: string): string {.tags: [FReadDir].} = ## notation is supported. when defined(windows): var - f: TWin32FindData + f: TWIN32_FIND_DATA res: int - res = findfirstFile(pattern, f) + res = findFirstFile(pattern, f) if res != -1: while true: if not skipFindData(f): yield splitFile(pattern).dir / extractFilename(getFilename(f)) if findnextFile(res, f) == 0'i32: break - findclose(res) + findClose(res) else: # here we use glob var f: TGlob @@ -1205,8 +1205,8 @@ iterator walkDir*(dir: string): tuple[kind: TPathComponent, path: string] {. ## dirA/fileA1.txt ## dirA/fileA2.txt when defined(windows): - var f: TWIN32_Find_Data - var h = findfirstFile(dir / "*", f) + var f: TWIN32_FIND_DATA + var h = findFirstFile(dir / "*", f) if h != -1: while true: var k = pcFile @@ -1215,7 +1215,7 @@ iterator walkDir*(dir: string): tuple[kind: TPathComponent, path: string] {. k = pcDir yield (k, dir / extractFilename(getFilename(f))) if findnextFile(h, f) == 0'i32: break - findclose(h) + findClose(h) else: var d = openDir(dir) if d != nil: @@ -1553,7 +1553,7 @@ proc getAppFilename*(): string {.rtl, extern: "nos$1", tags: [FReadIO].} = # /proc/<pid>/file when defined(windows): when useWinUnicode: - var buf = cast[wideCString](alloc(256*2)) + var buf = cast[WideCString](alloc(256*2)) var len = getModuleFileNameW(0, buf, 256) result = buf$len else: @@ -1614,15 +1614,15 @@ proc sleep*(milsecs: int) {.rtl, extern: "nos$1", tags: [FTime].} = a.tv_nsec = (milsecs mod 1000) * 1000 * 1000 discard posix.nanosleep(a, b) -proc getFileSize*(file: string): biggestInt {.rtl, extern: "nos$1", +proc getFileSize*(file: string): BiggestInt {.rtl, extern: "nos$1", tags: [FReadIO].} = ## returns the file size of `file`. Can raise ``EOS``. when defined(windows): - var a: TWin32FindData - var resA = findfirstFile(file, a) + var a: TWIN32_FIND_DATA + var resA = findFirstFile(file, a) if resA == -1: osError(osLastError()) result = rdFileSize(a) - findclose(resA) + findClose(resA) else: var f: TFile if open(f, file): diff --git a/lib/pure/osproc.nim b/lib/pure/osproc.nim index 1f04b7902..49b4b6fab 100644 --- a/lib/pure/osproc.nim +++ b/lib/pure/osproc.nim @@ -23,7 +23,7 @@ else: type TProcess = object of TObject when defined(windows): - FProcessHandle: Thandle + FProcessHandle: THandle inHandle, outHandle, errHandle: TFileHandle id: THandle else: @@ -108,7 +108,7 @@ proc execCmd*(command: string): int {.rtl, extern: "nosp$1", tags: [FExecIO].} proc startProcess*(command: string, workingDir: string = "", - args: openarray[string] = [], + args: openArray[string] = [], env: PStringTable = nil, options: set[TProcessOption] = {poStdErrToStdOut}): PProcess {.rtl, extern: "nosp$1", tags: [FExecIO, FReadEnv].} @@ -219,7 +219,7 @@ proc countProcessors*(): int {.rtl, extern: "nosp$1".} = ## returns the numer of the processors/cores the machine has. ## Returns 0 if it cannot be detected. when defined(windows): - var x = getenv("NUMBER_OF_PROCESSORS") + var x = getEnv("NUMBER_OF_PROCESSORS") if x.len > 0: result = parseInt(x.string) elif defined(macosx) or defined(bsd): var @@ -358,7 +358,7 @@ when defined(Windows) and not defined(useNimRtl): result.readDataImpl = hsReadData result.writeDataImpl = hsWriteData - proc buildCommandLine(a: string, args: openarray[string]): cstring = + proc buildCommandLine(a: string, args: openArray[string]): cstring = var res = quoteShell(a) for i in 0..high(args): res.add(' ') @@ -384,11 +384,11 @@ when defined(Windows) and not defined(useNimRtl): # O_RDONLY {.importc: "_O_RDONLY", header: "<fcntl.h>".}: int proc createPipeHandles(Rdhandle, WrHandle: var THandle) = - var piInheritablePipe: TSecurityAttributes - piInheritablePipe.nlength = SizeOf(TSecurityAttributes).cint + var piInheritablePipe: TSECURITY_ATTRIBUTES + piInheritablePipe.nlength = sizeof(TSECURITY_ATTRIBUTES).cint piInheritablePipe.lpSecurityDescriptor = nil piInheritablePipe.Binherithandle = 1 - if createPipe(Rdhandle, Wrhandle, piInheritablePipe, 1024) == 0'i32: + if createPipe(Rdhandle, WrHandle, piInheritablePipe, 1024) == 0'i32: osError(osLastError()) proc fileClose(h: THandle) {.inline.} = @@ -400,28 +400,28 @@ when defined(Windows) and not defined(useNimRtl): env: PStringTable = nil, options: set[TProcessOption] = {poStdErrToStdOut}): PProcess = var - si: TStartupInfo - procInfo: TProcessInformation + si: TSTARTUPINFO + procInfo: TPROCESS_INFORMATION success: int hi, ho, he: THandle new(result) - SI.cb = SizeOf(SI).cint + si.cb = sizeof(si).cint if poParentStreams notin options: - SI.dwFlags = STARTF_USESTDHANDLES # STARTF_USESHOWWINDOW or - CreatePipeHandles(SI.hStdInput, HI) - CreatePipeHandles(HO, Si.hStdOutput) + si.dwFlags = STARTF_USESTDHANDLES # STARTF_USESHOWWINDOW or + createPipeHandles(si.hStdInput, hi) + createPipeHandles(ho, si.hStdOutput) if poStdErrToStdOut in options: - SI.hStdError = SI.hStdOutput - HE = HO + si.hStdError = si.hStdOutput + he = ho else: - CreatePipeHandles(HE, Si.hStdError) + createPipeHandles(he, si.hStdError) result.inHandle = TFileHandle(hi) result.outHandle = TFileHandle(ho) result.errHandle = TFileHandle(he) else: - SI.hStdError = GetStdHandle(STD_ERROR_HANDLE) - SI.hStdInput = GetStdHandle(STD_INPUT_HANDLE) - SI.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE) + 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) @@ -442,17 +442,17 @@ when defined(Windows) and not defined(useNimRtl): var wwd = newWideCString(wd) success = winlean.CreateProcessW(nil, tmp, nil, nil, 1, NORMAL_PRIORITY_CLASS or CREATE_UNICODE_ENVIRONMENT, - ee, wwd, SI, ProcInfo) + ee, wwd, si, procInfo) else: success = winlean.CreateProcessA(nil, cmdl, nil, nil, 1, NORMAL_PRIORITY_CLASS, e, wd, SI, ProcInfo) let lastError = osLastError() if poParentStreams notin options: - FileClose(si.hStdInput) - FileClose(si.hStdOutput) + fileClose(si.hStdInput) + fileClose(si.hStdOutput) if poStdErrToStdOut notin options: - FileClose(si.hStdError) + fileClose(si.hStdError) if e != nil: dealloc(e) dealloc(cmdl) @@ -471,10 +471,10 @@ when defined(Windows) and not defined(useNimRtl): discard CloseHandle(p.FProcessHandle) proc suspend(p: PProcess) = - discard SuspendThread(p.FProcessHandle) + discard suspendThread(p.FProcessHandle) proc resume(p: PProcess) = - discard ResumeThread(p.FProcessHandle) + discard resumeThread(p.FProcessHandle) proc running(p: PProcess): bool = var x = waitForSingleObject(p.FProcessHandle, 50) @@ -482,22 +482,22 @@ when defined(Windows) and not defined(useNimRtl): proc terminate(p: PProcess) = if running(p): - discard TerminateProcess(p.FProcessHandle, 0) + discard terminateProcess(p.FProcessHandle, 0) proc waitForExit(p: PProcess, timeout: int = -1): int = - discard WaitForSingleObject(p.FProcessHandle, timeout.int32) + discard waitForSingleObject(p.FProcessHandle, timeout.int32) var res: int32 - discard GetExitCodeProcess(p.FProcessHandle, res) + discard getExitCodeProcess(p.FProcessHandle, res) result = res - discard CloseHandle(p.FProcessHandle) + discard closeHandle(p.FProcessHandle) proc peekExitCode(p: PProcess): int = var b = waitForSingleObject(p.FProcessHandle, 50) == WAIT_TIMEOUT if b: result = -1 else: var res: int32 - discard GetExitCodeProcess(p.FProcessHandle, res) + discard getExitCodeProcess(p.FProcessHandle, res) return res proc inputStream(p: PProcess): PStream = @@ -511,32 +511,32 @@ when defined(Windows) and not defined(useNimRtl): proc execCmd(command: string): int = var - si: TStartupInfo - procInfo: TProcessInformation + si: TSTARTUPINFO + procInfo: TPROCESS_INFORMATION process: THandle L: int32 - SI.cb = SizeOf(SI).cint - SI.hStdError = GetStdHandle(STD_ERROR_HANDLE) - SI.hStdInput = GetStdHandle(STD_INPUT_HANDLE) - SI.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE) + si.cb = sizeof(si).cint + si.hStdError = getStdHandle(STD_ERROR_HANDLE) + si.hStdInput = getStdHandle(STD_INPUT_HANDLE) + si.hStdOutput = getStdHandle(STD_OUTPUT_HANDLE) when useWinUnicode: var c = newWideCString(command) var res = winlean.CreateProcessW(nil, c, nil, nil, 0, - NORMAL_PRIORITY_CLASS, nil, nil, SI, ProcInfo) + NORMAL_PRIORITY_CLASS, nil, nil, si, procInfo) else: var res = winlean.CreateProcessA(nil, command, nil, nil, 0, NORMAL_PRIORITY_CLASS, nil, nil, SI, ProcInfo) if res == 0: osError(osLastError()) else: - Process = ProcInfo.hProcess - discard CloseHandle(ProcInfo.hThread) - if WaitForSingleObject(Process, INFINITE) != -1: - discard GetExitCodeProcess(Process, L) + process = procInfo.hProcess + discard closeHandle(procInfo.hThread) + if waitForSingleObject(process, INFINITE) != -1: + discard getExitCodeProcess(process, L) result = int(L) else: result = -1 - discard CloseHandle(Process) + discard closeHandle(process) proc select(readfds: var seq[PProcess], timeout = 500): int = assert readfds.len <= MAXIMUM_WAIT_OBJECTS diff --git a/lib/pure/parseopt.nim b/lib/pure/parseopt.nim index fa704bbce..1be292af1 100644 --- a/lib/pure/parseopt.nim +++ b/lib/pure/parseopt.nim @@ -50,7 +50,7 @@ when defined(os.ParamCount): result.cmd = cmdline else: result.cmd = "" - for i in countup(1, ParamCount()): + for i in countup(1, paramCount()): result.cmd = result.cmd & quoteIfContainsWhite(paramStr(i).string) & ' ' result.kind = cmdEnd result.key = TaintedString"" @@ -94,8 +94,8 @@ proc next*(p: var TOptParser) {. var i = p.pos while p.cmd[i] in {'\x09', ' '}: inc(i) p.pos = i - setlen(p.key.string, 0) - setlen(p.val.string, 0) + setLen(p.key.string, 0) + setLen(p.val.string, 0) if p.inShortState: handleShortOption(p) return diff --git a/lib/pure/parseutils.nim b/lib/pure/parseutils.nim index bccb274d6..6423b3ab0 100644 --- a/lib/pure/parseutils.nim +++ b/lib/pure/parseutils.nim @@ -189,7 +189,7 @@ proc captureBetween*(s: string, first: char, second = '\0', start = 0): string = {.push overflowChecks: on.} # this must be compiled with overflow checking turned on: -proc rawParseInt(s: string, b: var biggestInt, start = 0): int = +proc rawParseInt(s: string, b: var BiggestInt, start = 0): int = var sign: BiggestInt = -1 i = start @@ -207,12 +207,12 @@ proc rawParseInt(s: string, b: var biggestInt, start = 0): int = result = i - start {.pop.} # overflowChecks -proc parseBiggestInt*(s: string, number: var biggestInt, start = 0): int {. +proc parseBiggestInt*(s: string, number: var BiggestInt, start = 0): int {. rtl, extern: "npuParseBiggestInt", noSideEffect.} = ## parses an integer starting at `start` and stores the value into `number`. ## Result is the number of processed chars or 0 if there is no integer. ## `EOverflow` is raised if an overflow occurs. - var res: biggestInt + var res: BiggestInt # use 'res' for exception safety (don't write to 'number' in case of an # overflow exception: result = rawParseInt(s, res, start) @@ -223,7 +223,7 @@ proc parseInt*(s: string, number: var int, start = 0): int {. ## parses an integer starting at `start` and stores the value into `number`. ## Result is the number of processed chars or 0 if there is no integer. ## `EOverflow` is raised if an overflow occurs. - var res: biggestInt + var res: BiggestInt result = parseBiggestInt(s, res, start) if (sizeof(int) <= 4) and ((res < low(int)) or (res > high(int))): @@ -231,7 +231,7 @@ proc parseInt*(s: string, number: var int, start = 0): int {. else: number = int(res) -proc tenToThePowerOf(b: int): biggestFloat = +proc tenToThePowerOf(b: int): BiggestFloat = var b = b var a = 10.0 result = 1.0 @@ -242,7 +242,7 @@ proc tenToThePowerOf(b: int): biggestFloat = if b == 0: break a *= a -proc parseBiggestFloat*(s: string, number: var biggestFloat, start = 0): int {. +proc parseBiggestFloat*(s: string, number: var BiggestFloat, start = 0): int {. rtl, extern: "npuParseBiggestFloat", noSideEffect.} = ## parses a float starting at `start` and stores the value into `number`. ## Result is the number of processed chars or 0 if there occured a parsing @@ -319,7 +319,7 @@ proc parseFloat*(s: string, number: var float, start = 0): int {. ## parses a float starting at `start` and stores the value into `number`. ## Result is the number of processed chars or 0 if there occured a parsing ## error. - var bf: biggestFloat + var bf: BiggestFloat result = parseBiggestFloat(s, bf, start) number = bf diff --git a/lib/pure/sockets.nim b/lib/pure/sockets.nim index f5351c41c..2ae37e372 100644 --- a/lib/pure/sockets.nim +++ b/lib/pure/sockets.nim @@ -362,28 +362,28 @@ proc socketError*(socket: TSocket, err: int = -1, async = false) = else: SSLError("Unknown Error") if err == -1 and not (when defined(ssl): socket.isSSL else: false): - let lastError = OSLastError() + let lastError = osLastError() if async: when defined(windows): if lastError.int32 == WSAEWOULDBLOCK: return - else: OSError(lastError) + else: osError(lastError) else: if lastError.int32 == EAGAIN or lastError.int32 == EWOULDBLOCK: return else: OSError(lastError) - else: OSError(lastError) + else: osError(lastError) proc listen*(socket: TSocket, backlog = SOMAXCONN) {.tags: [FReadIO].} = ## 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()) + if listen(socket.fd, cint(backlog)) < 0'i32: osError(osLastError()) proc invalidIp4(s: string) {.noreturn, noinline.} = raise newException(EInvalidValue, "invalid ip4 address: " & s) -proc parseIp4*(s: string): biggestInt = +proc parseIp4*(s: string): BiggestInt = ## parses an IP version 4 in dotted decimal form like "a.b.c.d". ## ## This is equivalent to `inet_ntoa`:idx:. @@ -410,14 +410,14 @@ proc parseIp4*(s: string): biggestInt = if j <= 0: invalidIp4(s) inc(i, j) if s[i] != '\0': invalidIp4(s) - result = biggestInt(a shl 24 or b shl 16 or c shl 8 or d) + result = BiggestInt(a shl 24 or b shl 16 or c shl 8 or d) template gaiNim(a, p, h, list: expr): stmt = block: - var gaiResult = getAddrInfo(a, $p, addr(h), list) + var gaiResult = getaddrinfo(a, $p, addr(h), list) if gaiResult != 0'i32: when defined(windows): - OSError(OSLastError()) + osError(osLastError()) else: raise newException(EOS, $gai_strerror(gaiResult)) @@ -437,7 +437,7 @@ proc bindAddr*(socket: TSocket, port = TPort(0), address = "") {. name.sin_addr.s_addr = sockets.htonl(INADDR_ANY) if bindSocket(socket.fd, cast[ptr TSockAddr](addr(name)), sizeof(name).TSockLen) < 0'i32: - OSError(OSLastError()) + osError(osLastError()) else: var hints: TAddrInfo var aiList: ptr TAddrInfo = nil @@ -446,7 +446,7 @@ proc bindAddr*(socket: TSocket, port = TPort(0), address = "") {. hints.ai_protocol = toInt(IPPROTO_TCP) gaiNim(address, port, hints, aiList) if bindSocket(socket.fd, aiList.ai_addr, aiList.ai_addrLen.TSockLen) < 0'i32: - OSError(OSLastError()) + osError(osLastError()) proc getSockName*(socket: TSocket): TPort = ## returns the socket's associated port number. @@ -460,37 +460,37 @@ proc getSockName*(socket: TSocket): TPort = var namelen = sizeof(name).TSockLen if getsockname(socket.fd, cast[ptr TSockAddr](addr(name)), addr(namelen)) == -1'i32: - OSError(OSLastError()) + osError(osLastError()) result = TPort(sockets.ntohs(name.sin_port)) 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)) if sock == osInvalidSocket: - let err = OSLastError() + let err = osLastError() when defined(windows): if err.int32 == WSAEINPROGRESS: - client = InvalidSocket + client = invalidSocket address = "" when noClientRet.int == -1: return else: return noClientRet - else: OSError(err) + else: osError(err) else: if err.int32 == EAGAIN or err.int32 == EWOULDBLOCK: - client = InvalidSocket + client = invalidSocket address = "" when noClientRet.int == -1: return else: return noClientRet - else: OSError(err) + else: osError(err) else: client.fd = sock client.isBuffered = server.isBuffered @@ -669,7 +669,7 @@ proc getServByPort*(port: TPort, proto: string): TServent {.tags: [FReadIO].} = result.port = TPort(s.s_port) result.proto = $s.s_proto -proc getHostByAddr*(ip: string): THostEnt {.tags: [FReadIO].} = +proc getHostByAddr*(ip: string): Thostent {.tags: [FReadIO].} = ## This function will lookup the hostname of an IP Address. var myaddr: TInAddr myaddr.s_addr = inet_addr(ip) @@ -677,7 +677,7 @@ proc getHostByAddr*(ip: string): THostEnt {.tags: [FReadIO].} = when defined(windows): var s = winlean.gethostbyaddr(addr(myaddr), sizeof(myaddr).cuint, cint(sockets.AF_INET)) - if s == nil: OSError(OSLastError()) + if s == nil: osError(osLastError()) else: var s = posix.gethostbyaddr(addr(myaddr), sizeof(myaddr).TSockLen, cint(posix.AF_INET)) @@ -698,13 +698,13 @@ 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: [FReadIO].} = ## This function will lookup the IP address of a hostname. when defined(Windows): var s = winlean.gethostbyname(name) else: var s = posix.gethostbyname(name) - if s == nil: OSError(OSLastError()) + if s == nil: osError(osLastError()) result.name = $s.h_name result.aliases = cstringArrayToSeq(s.h_aliases) when defined(windows): @@ -726,7 +726,7 @@ proc getSockOptInt*(socket: TSocket, level, optname: int): int {. var size = sizeof(res).TSockLen if getsockopt(socket.fd, cint(level), cint(optname), addr(res), addr(size)) < 0'i32: - OSError(OSLastError()) + osError(osLastError()) result = int(res) proc setSockOptInt*(socket: TSocket, level, optname, optval: int) {. @@ -735,7 +735,7 @@ proc setSockOptInt*(socket: TSocket, level, optname, optval: int) {. var value = cint(optval) if setsockopt(socket.fd, cint(level), cint(optname), addr(value), sizeof(value).TSockLen) < 0'i32: - OSError(OSLastError()) + osError(osLastError()) proc toCInt(opt: TSOBool): cint = case opt @@ -754,7 +754,7 @@ proc getSockOpt*(socket: TSocket, opt: TSOBool, level = SOL_SOCKET): bool {. var size = sizeof(res).TSockLen if getsockopt(socket.fd, cint(level), toCInt(opt), addr(res), addr(size)) < 0'i32: - OSError(OSLastError()) + osError(osLastError()) result = res != 0 proc setSockOpt*(socket: TSocket, opt: TSOBool, value: bool, level = SOL_SOCKET) {. @@ -763,7 +763,7 @@ proc setSockOpt*(socket: TSocket, opt: TSOBool, value: bool, level = SOL_SOCKET) var valuei = cint(if value: 1 else: 0) if setsockopt(socket.fd, cint(level), toCInt(opt), addr(valuei), sizeof(valuei).TSockLen) < 0'i32: - OSError(OSLastError()) + osError(osLastError()) proc connect*(socket: TSocket, address: string, port = TPort(0), af: TDomain = AF_INET) {.tags: [FReadIO].} = @@ -787,11 +787,11 @@ proc connect*(socket: TSocket, address: string, port = TPort(0), if connect(socket.fd, it.ai_addr, it.ai_addrlen.TSockLen) == 0'i32: success = true break - else: lastError = OSLastError() + else: lastError = osLastError() it = it.ai_next freeaddrinfo(aiList) - if not success: OSError(lastError) + if not success: osError(lastError) when defined(ssl): if socket.isSSL: @@ -852,7 +852,7 @@ proc connectAsync*(socket: TSocket, name: string, port = TPort(0), success = true break else: - lastError = OSLastError() + lastError = osLastError() when defined(windows): # Windows EINTR doesn't behave same as POSIX. if lastError.int32 == WSAEWOULDBLOCK: @@ -866,7 +866,7 @@ proc connectAsync*(socket: TSocket, name: string, port = TPort(0), it = it.ai_next freeaddrinfo(aiList) - if not success: OSError(lastError) + if not success: osError(lastError) when defined(ssl): if socket.isSSL: socket.sslNoHandshake = true @@ -912,7 +912,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 @@ -970,7 +970,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,7 +993,7 @@ proc select*(readfds, writefds: var seq[TSocket], 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 @@ -1017,7 +1017,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 @@ -1035,7 +1035,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 @@ -1142,7 +1142,7 @@ proc waitFor(socket: TSocket, waited: var float, timeout, size: int, var s = @[socket] var startTime = epochTime() let selRet = select(s, timeout - int(waited * 1000.0)) - if selRet < 0: OSError(OSLastError()) + if selRet < 0: osError(osLastError()) if selRet != 1: raise newException(ETimeout, "Call to '" & funcName & "' timed out.") waited += (epochTime() - startTime) @@ -1180,7 +1180,7 @@ proc recv*(socket: TSocket, data: var string, size: int, timeout = -1): int = result = recv(socket, cstring(data), size, timeout) if result < 0: data.setLen(0) - socket.SocketError(result) + socket.socketError(result) data.setLen(result) proc recvAsync*(socket: TSocket, data: var string, size: int): int = @@ -1194,7 +1194,7 @@ proc recvAsync*(socket: TSocket, data: var string, size: int): int = result = recv(socket, cstring(data), size) if result < 0: data.setLen(0) - socket.SocketError(async = true) + socket.socketError(async = true) result = -1 data.setLen(result) @@ -1291,14 +1291,14 @@ proc readLine*(socket: TSocket, line: var TaintedString, timeout = -1) {. var c: char discard waitFor(socket, waited, timeout, 1, "readLine") var n = recv(socket, addr(c), 1) - if n < 0: OSError(OSLastError()) + if n < 0: osError(osLastError()) elif n == 0: return if c == '\r': discard waitFor(socket, waited, timeout, 1, "readLine") n = peekChar(socket, c) if n > 0 and c == '\L': discard recv(socket, addr(c), 1) - elif n <= 0: OSError(OSLastError()) + elif n <= 0: osError(osLastError()) addNlIfEmpty() return elif c == '\L': @@ -1352,7 +1352,7 @@ proc readLineAsync*(socket: TSocket, setLen(line.string, 0) template errorOrNone = - socket.SocketError(async = true) + socket.socketError(async = true) return ReadNone while true: @@ -1385,7 +1385,7 @@ proc recv*(socket: TSocket): TaintedString {.tags: [FReadIO], deprecated.} = var pos = 0 while true: var bytesRead = recv(socket, addr(string(result)[pos]), bufSize-1) - if bytesRead == -1: OSError(OSLastError()) + if bytesRead == -1: osError(osLastError()) setLen(result.string, pos + bytesRead) if bytesRead != bufSize-1: break # increase capacity: @@ -1454,11 +1454,11 @@ proc recvAsync*(socket: TSocket, s: var TaintedString): bool {. else: SSLError("Unknown Error") if bytesRead == -1 and not (when defined(ssl): socket.isSSL else: false): - let err = OSLastError() + let err = osLastError() when defined(windows): if err.int32 == WSAEWOULDBLOCK: return False - else: OSError(err) + else: osError(err) else: if err.int32 == EAGAIN or err.int32 == EWOULDBLOCK: return False @@ -1489,7 +1489,7 @@ proc recvFrom*(socket: TSocket, data: var string, length: int, data.setLen(length) var sockAddress: Tsockaddr_in var addrLen = sizeof(sockAddress).TSockLen - result = recvFrom(socket.fd, cstring(data), length.cint, flags.cint, + result = recvfrom(socket.fd, cstring(data), length.cint, flags.cint, cast[ptr TSockAddr](addr(sockAddress)), addr(addrLen)) if result != -1: @@ -1497,7 +1497,7 @@ proc recvFrom*(socket: TSocket, data: var string, length: int, address = $inet_ntoa(sockAddress.sin_addr) port = ntohs(sockAddress.sin_port).TPort -proc recvFromAsync*(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].} = ## Variant of ``recvFrom`` for non-blocking sockets. Unlike ``recvFrom``, @@ -1507,11 +1507,11 @@ proc recvFromAsync*(socket: TSocket, data: var String, length: int, result = true var callRes = recvFrom(socket, data, length, address, port, flags) if callRes < 0: - let err = OSLastError() + let err = osLastError() when defined(windows): if err.int32 == WSAEWOULDBLOCK: return False - else: OSError(err) + else: osError(err) else: if err.int32 == EAGAIN or err.int32 == EWOULDBLOCK: return False @@ -1565,7 +1565,7 @@ proc send*(socket: TSocket, data: string) {.tags: [FWriteIO].} = if socket.isSSL: SSLError() - OSError(OSLastError()) + osError(osLastError()) if sent != data.len: raise newException(EOS, "Could not send all data.") @@ -1598,11 +1598,11 @@ proc sendAsync*(socket: TSocket, data: string): int {.tags: [FWriteIO].} = else: return if result == -1: - let err = OSLastError() + let err = osLastError() when defined(windows): if err.int32 == WSAEINPROGRESS: return 0 - else: OSError(err) + else: osError(err) else: if err.int32 == EAGAIN or err.int32 == EWOULDBLOCK: return 0 @@ -1633,7 +1633,7 @@ proc sendTo*(socket: TSocket, address: string, port: TPort, data: pointer, var success = false var it = aiList while it != nil: - result = sendTo(socket.fd, data, size.cint, flags.cint, it.ai_addr, + result = sendto(socket.fd, data, size.cint, flags.cint, it.ai_addr, it.ai_addrlen.TSockLen) if result != -1'i32: success = true @@ -1662,7 +1662,7 @@ proc setBlocking(s: TSocket, blocking: bool) = when defined(Windows): var mode = clong(ord(not blocking)) # 1 for non-blocking, 0 for blocking if ioctlsocket(s.fd, FIONBIO, addr(mode)) == -1: - OSError(OSLastError()) + osError(osLastError()) else: # BSD sockets var x: int = fcntl(s.fd, F_GETFL, 0) if x == -1: @@ -1709,7 +1709,7 @@ proc isBlocking*(socket: TSocket): bool = not socket.nonblocking ## Determines whether ``socket`` is blocking. when defined(Windows): - var wsa: TWSADATA - if WSAStartup(0x0101'i16, addr wsa) != 0: OSError(OSLastError()) + var wsa: TWSAData + if WSAStartup(0x0101'i16, addr wsa) != 0: osError(osLastError()) diff --git a/lib/pure/streams.nim b/lib/pure/streams.nim index 764471b78..302742eb4 100644 --- a/lib/pure/streams.nim +++ b/lib/pure/streams.nim @@ -249,7 +249,7 @@ proc fsClose(s: PStream) = close(PFileStream(s).f) PFileStream(s).f = nil proc fsFlush(s: PStream) = flushFile(PFileStream(s).f) -proc fsAtEnd(s: PStream): bool = return EndOfFile(PFileStream(s).f) +proc fsAtEnd(s: PStream): bool = return endOfFile(PFileStream(s).f) proc fsSetPosition(s: PStream, pos: int) = setFilePos(PFileStream(s).f, pos) proc fsGetPosition(s: PStream): int = return int(getFilePos(PFileStream(s).f)) @@ -277,7 +277,7 @@ proc newFileStream*(filename: string, mode: TFileMode): PFileStream = ## 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 - if Open(f, filename, mode): result = newFileStream(f) + if open(f, filename, mode): result = newFileStream(f) when true: diff --git a/lib/pure/strtabs.nim b/lib/pure/strtabs.nim index d8bc94176..7003acfcf 100644 --- a/lib/pure/strtabs.nim +++ b/lib/pure/strtabs.nim @@ -91,7 +91,7 @@ proc nextTry(h, maxHash: THash): THash {.inline.} = proc rawGet(t: PStringTable, key: string): int = var h: THash = myhash(t, key) and high(t.data) # start with real hash value while not isNil(t.data[h].key): - if mycmp(t, t.data[h].key, key): + if myCmp(t, t.data[h].key, key): return h h = nextTry(h, high(t.data)) result = - 1 @@ -100,7 +100,7 @@ proc `[]`*(t: PStringTable, key: string): string {.rtl, extern: "nstGet".} = ## retrieves the value at ``t[key]``. If `key` is not in `t`, "" is returned ## and no exception is raised. One can check with ``hasKey`` whether the key ## exists. - var index = RawGet(t, key) + var index = rawGet(t, key) if index >= 0: result = t.data[index].val else: result = "" @@ -108,7 +108,7 @@ proc mget*(t: PStringTable, key: string): var string {. rtl, extern: "nstTake".} = ## retrieves the location at ``t[key]``. If `key` is not in `t`, the ## ``EInvalidKey`` exception is raised. - var index = RawGet(t, key) + var index = rawGet(t, key) if index >= 0: result = t.data[index].val else: raise newException(EInvalidKey, "key does not exist: " & key) @@ -127,17 +127,17 @@ proc enlarge(t: PStringTable) = var n: TKeyValuePairSeq newSeq(n, len(t.data) * growthFactor) for i in countup(0, high(t.data)): - if not isNil(t.data[i].key): RawInsert(t, n, t.data[i].key, t.data[i].val) + if not isNil(t.data[i].key): rawInsert(t, n, t.data[i].key, t.data[i].val) swap(t.data, n) proc `[]=`*(t: PStringTable, key, val: string) {.rtl, extern: "nstPut".} = ## puts a (key, value)-pair into `t`. - var index = RawGet(t, key) + var index = rawGet(t, key) if index >= 0: t.data[index].val = val else: - if mustRehash(len(t.data), t.counter): Enlarge(t) - RawInsert(t, t.data, key, val) + if mustRehash(len(t.data), t.counter): enlarge(t) + rawInsert(t, t.data, key, val) inc(t.counter) proc raiseFormatException(s: string) = @@ -184,7 +184,7 @@ proc newStringTable*(keyValuePairs: varargs[tuple[key, val: string]], ## var mytab = newStringTable({"key1": "val1", "key2": "val2"}, ## modeCaseInsensitive) result = newStringTable(mode) - for key, val in items(keyvaluePairs): result[key] = val + for key, val in items(keyValuePairs): result[key] = val proc `%`*(f: string, t: PStringTable, flags: set[TFormatFlag] = {}): string {. rtl, extern: "nstFormat".} = diff --git a/lib/pure/strutils.nim b/lib/pure/strutils.nim index 388a76e71..b7e3de6cf 100644 --- a/lib/pure/strutils.nim +++ b/lib/pure/strutils.nim @@ -1,170 +1,170 @@ -# -# -# Nimrod's Runtime Library -# (c) Copyright 2012 Andreas Rumpf -# -# See the file "copying.txt", included in this -# distribution, for details about the copyright. -# - -## This module contains various string utility routines. -## See the module `re <re.html>`_ for regular expression support. -## See the module `pegs <pegs.html>`_ for PEG support. - -import parseutils - -{.deadCodeElim: on.} - -{.push debugger:off .} # the user does not want to trace a part - # of the standard library! - -include "system/inclrtl" - -type - TCharSet* = set[char] # for compatibility with Nim - -const - Whitespace* = {' ', '\t', '\v', '\r', '\l', '\f'} - ## All the characters that count as whitespace. - - Letters* = {'A'..'Z', 'a'..'z'} - ## the set of letters - - Digits* = {'0'..'9'} - ## the set of digits - - HexDigits* = {'0'..'9', 'A'..'F', 'a'..'f'} - ## the set of hexadecimal digits - - IdentChars* = {'a'..'z', 'A'..'Z', '0'..'9', '_'} - ## the set of characters an identifier can consist of - - IdentStartChars* = {'a'..'z', 'A'..'Z', '_'} - ## the set of characters an identifier can start with - - NewLines* = {'\13', '\10'} - ## the set of characters a newline terminator can start with - -proc toLower*(c: Char): Char {.noSideEffect, procvar, - rtl, extern: "nsuToLowerChar".} = - ## Converts `c` into lower case. This works only for the letters A-Z. - ## See `unicode.toLower` for a version that works for any Unicode character. - if c in {'A'..'Z'}: - result = chr(ord(c) + (ord('a') - ord('A'))) - else: - result = c - -proc toLower*(s: string): string {.noSideEffect, procvar, - rtl, extern: "nsuToLowerStr".} = - ## Converts `s` into lower case. This works only for the letters A-Z. - ## See `unicode.toLower` for a version that works for any Unicode character. - result = newString(len(s)) - for i in 0..len(s) - 1: - result[i] = toLower(s[i]) - -proc toUpper*(c: Char): Char {.noSideEffect, procvar, - rtl, extern: "nsuToUpperChar".} = - ## Converts `c` into upper case. This works only for the letters a-z. - ## See `unicode.toUpper` for a version that works for any Unicode character. - if c in {'a'..'z'}: - result = Chr(Ord(c) - (Ord('a') - Ord('A'))) - else: - result = c - -proc toUpper*(s: string): string {.noSideEffect, procvar, - rtl, extern: "nsuToUpperStr".} = - ## Converts `s` into upper case. This works only for the letters a-z. - ## See `unicode.toUpper` for a version that works for any Unicode character. - result = newString(len(s)) - for i in 0..len(s) - 1: - result[i] = toUpper(s[i]) - -proc capitalize*(s: string): string {.noSideEffect, procvar, - rtl, extern: "nsuCapitalize".} = - ## Converts the first character of `s` into upper case. - ## This works only for the letters a-z. - result = toUpper(s[0]) & substr(s, 1) - -proc normalize*(s: string): string {.noSideEffect, procvar, - rtl, extern: "nsuNormalize".} = - ## Normalizes the string `s`. That means to convert it to lower case and - ## remove any '_'. This is needed for Nimrod identifiers for example. - result = newString(s.len) - var j = 0 - for i in 0..len(s) - 1: - if s[i] in {'A'..'Z'}: - result[j] = chr(ord(s[i]) + (ord('a') - ord('A'))) - inc j - elif s[i] != '_': - result[j] = s[i] - inc j - if j != s.len: setLen(result, j) - -proc cmpIgnoreCase*(a, b: string): int {.noSideEffect, - rtl, extern: "nsuCmpIgnoreCase", procvar, operator: 4.} = - ## Compares two strings in a case insensitive manner. Returns: - ## - ## | 0 iff a == b - ## | < 0 iff a < b - ## | > 0 iff a > b - var i = 0 - var m = min(a.len, b.len) - while i < m: - result = ord(toLower(a[i])) - ord(toLower(b[i])) - if result != 0: return - inc(i) - result = a.len - b.len - -{.push checks: off, line_trace: off .} # this is a hot-spot in the compiler! - # thus we compile without checks here - -proc cmpIgnoreStyle*(a, b: string): int {.noSideEffect, - rtl, extern: "nsuCmpIgnoreStyle", procvar, operator: 3.} = - ## Compares two strings normalized (i.e. case and - ## underscores do not matter). Returns: - ## - ## | 0 iff a == b - ## | < 0 iff a < b - ## | > 0 iff a > b - var i = 0 - var j = 0 - while true: - while a[i] == '_': inc(i) - while b[j] == '_': inc(j) # BUGFIX: typo - var aa = toLower(a[i]) - var bb = toLower(b[j]) - result = ord(aa) - ord(bb) - if result != 0 or aa == '\0': break - inc(i) - inc(j) - -{.pop.} - -proc strip*(s: string, leading = true, trailing = true): string {.noSideEffect, - rtl, extern: "nsuStrip", operator: 5.} = - ## Strips whitespace from `s` and returns the resulting string. - ## If `leading` is true, leading whitespace is stripped. - ## If `trailing` is true, trailing whitespace is stripped. - const - chars: set[Char] = Whitespace - var - first = 0 - last = len(s)-1 - if leading: - while s[first] in chars: inc(first) - if trailing: - while last >= 0 and s[last] in chars: dec(last) - result = substr(s, first, last) - -proc toOctal*(c: char): string {.noSideEffect, rtl, extern: "nsuToOctal".} = - ## Converts a character `c` to its octal representation. The resulting - ## string may not have a leading zero. Its length is always exactly 3. - result = newString(3) - var val = ord(c) - for i in countdown(2, 0): - result[i] = Chr(val mod 8 + ord('0')) - val = val div 8 - +# +# +# Nimrod's Runtime Library +# (c) Copyright 2012 Andreas Rumpf +# +# See the file "copying.txt", included in this +# distribution, for details about the copyright. +# + +## This module contains various string utility routines. +## See the module `re <re.html>`_ for regular expression support. +## See the module `pegs <pegs.html>`_ for PEG support. + +import parseutils + +{.deadCodeElim: on.} + +{.push debugger:off .} # the user does not want to trace a part + # of the standard library! + +include "system/inclrtl" + +type + TCharSet* = set[char] # for compatibility with Nim + +const + Whitespace* = {' ', '\t', '\v', '\r', '\l', '\f'} + ## All the characters that count as whitespace. + + Letters* = {'A'..'Z', 'a'..'z'} + ## the set of letters + + Digits* = {'0'..'9'} + ## the set of digits + + HexDigits* = {'0'..'9', 'A'..'F', 'a'..'f'} + ## the set of hexadecimal digits + + IdentChars* = {'a'..'z', 'A'..'Z', '0'..'9', '_'} + ## the set of characters an identifier can consist of + + IdentStartChars* = {'a'..'z', 'A'..'Z', '_'} + ## the set of characters an identifier can start with + + NewLines* = {'\13', '\10'} + ## the set of characters a newline terminator can start with + +proc toLower*(c: char): char {.noSideEffect, procvar, + rtl, extern: "nsuToLowerChar".} = + ## Converts `c` into lower case. This works only for the letters A-Z. + ## See `unicode.toLower` for a version that works for any Unicode character. + if c in {'A'..'Z'}: + result = chr(ord(c) + (ord('a') - ord('A'))) + else: + result = c + +proc toLower*(s: string): string {.noSideEffect, procvar, + rtl, extern: "nsuToLowerStr".} = + ## Converts `s` into lower case. This works only for the letters A-Z. + ## See `unicode.toLower` for a version that works for any Unicode character. + result = newString(len(s)) + for i in 0..len(s) - 1: + result[i] = toLower(s[i]) + +proc toUpper*(c: char): char {.noSideEffect, procvar, + rtl, extern: "nsuToUpperChar".} = + ## Converts `c` into upper case. This works only for the letters a-z. + ## See `unicode.toUpper` for a version that works for any Unicode character. + if c in {'a'..'z'}: + result = chr(ord(c) - (Ord('a') - Ord('A'))) + else: + result = c + +proc toUpper*(s: string): string {.noSideEffect, procvar, + rtl, extern: "nsuToUpperStr".} = + ## Converts `s` into upper case. This works only for the letters a-z. + ## See `unicode.toUpper` for a version that works for any Unicode character. + result = newString(len(s)) + for i in 0..len(s) - 1: + result[i] = toUpper(s[i]) + +proc capitalize*(s: string): string {.noSideEffect, procvar, + rtl, extern: "nsuCapitalize".} = + ## Converts the first character of `s` into upper case. + ## This works only for the letters a-z. + result = toUpper(s[0]) & substr(s, 1) + +proc normalize*(s: string): string {.noSideEffect, procvar, + rtl, extern: "nsuNormalize".} = + ## Normalizes the string `s`. That means to convert it to lower case and + ## remove any '_'. This is needed for Nimrod identifiers for example. + result = newString(s.len) + var j = 0 + for i in 0..len(s) - 1: + if s[i] in {'A'..'Z'}: + result[j] = chr(ord(s[i]) + (ord('a') - ord('A'))) + inc j + elif s[i] != '_': + result[j] = s[i] + inc j + if j != s.len: setLen(result, j) + +proc cmpIgnoreCase*(a, b: string): int {.noSideEffect, + rtl, extern: "nsuCmpIgnoreCase", procvar, operator: 4.} = + ## Compares two strings in a case insensitive manner. Returns: + ## + ## | 0 iff a == b + ## | < 0 iff a < b + ## | > 0 iff a > b + var i = 0 + var m = min(a.len, b.len) + while i < m: + result = ord(toLower(a[i])) - ord(toLower(b[i])) + if result != 0: return + inc(i) + result = a.len - b.len + +{.push checks: off, line_trace: off .} # this is a hot-spot in the compiler! + # thus we compile without checks here + +proc cmpIgnoreStyle*(a, b: string): int {.noSideEffect, + rtl, extern: "nsuCmpIgnoreStyle", procvar, operator: 3.} = + ## Compares two strings normalized (i.e. case and + ## underscores do not matter). Returns: + ## + ## | 0 iff a == b + ## | < 0 iff a < b + ## | > 0 iff a > b + var i = 0 + var j = 0 + while true: + while a[i] == '_': inc(i) + while b[j] == '_': inc(j) # BUGFIX: typo + var aa = toLower(a[i]) + var bb = toLower(b[j]) + result = ord(aa) - ord(bb) + if result != 0 or aa == '\0': break + inc(i) + inc(j) + +{.pop.} + +proc strip*(s: string, leading = true, trailing = true): string {.noSideEffect, + rtl, extern: "nsuStrip", operator: 5.} = + ## Strips whitespace from `s` and returns the resulting string. + ## If `leading` is true, leading whitespace is stripped. + ## If `trailing` is true, trailing whitespace is stripped. + const + chars: set[char] = Whitespace + var + first = 0 + last = len(s)-1 + if leading: + while s[first] in chars: inc(first) + if trailing: + while last >= 0 and s[last] in chars: dec(last) + result = substr(s, first, last) + +proc toOctal*(c: char): string {.noSideEffect, rtl, extern: "nsuToOctal".} = + ## Converts a character `c` to its octal representation. The resulting + ## string may not have a leading zero. Its length is always exactly 3. + result = newString(3) + var val = ord(c) + for i in countdown(2, 0): + result[i] = chr(val mod 8 + ord('0')) + val = val div 8 + iterator split*(s: string, seps: set[char] = Whitespace): string = ## Splits the string `s` into substrings using a group of separators. ## @@ -209,199 +209,199 @@ iterator split*(s: string, seps: set[char] = Whitespace): string = ## "08" ## "08.398990" ## - var last = 0 - assert(not ('\0' in seps)) - while last < len(s): - while s[last] in seps: inc(last) - var first = last - while last < len(s) and s[last] not_in seps: inc(last) # BUGFIX! - if first <= last-1: - yield substr(s, first, last-1) - -iterator split*(s: string, sep: char): string = - ## Splits the string `s` into substrings using a single separator. - ## - ## Substrings are separated by the character `sep`. - ## Unlike the version of the iterator which accepts a set of separator - ## characters, this proc will not coalesce groups of the - ## separator, returning a string for each found character. The code: - ## - ## .. code-block:: nimrod - ## for word in split(";;this;is;an;;example;;;", ';'): - ## writeln(stdout, word) - ## - ## Results in: - ## - ## .. code-block:: - ## "" - ## "" - ## "this" - ## "is" - ## "an" - ## "" - ## "example" - ## "" - ## "" - ## "" - ## - var last = 0 - assert('\0' != sep) - if len(s) > 0: - # `<=` is correct here for the edge cases! - while last <= len(s): - var first = last - while last < len(s) and s[last] != sep: inc(last) - yield substr(s, first, last-1) - inc(last) - -iterator splitLines*(s: string): string = - ## Splits the string `s` into its containing lines. Every newline - ## combination (CR, LF, CR-LF) is supported. The result strings contain - ## no trailing ``\n``. - ## - ## Example: - ## - ## .. code-block:: nimrod - ## for line in splitLines("\nthis\nis\nan\n\nexample\n"): - ## writeln(stdout, line) - ## - ## Results in: - ## - ## .. code-block:: nimrod - ## "" - ## "this" - ## "is" - ## "an" - ## "" - ## "example" - ## "" - var first = 0 - var last = 0 - while true: - while s[last] notin {'\0', '\c', '\l'}: inc(last) - yield substr(s, first, last-1) - # skip newlines: - if s[last] == '\l': inc(last) - elif s[last] == '\c': - inc(last) - if s[last] == '\l': inc(last) - else: break # was '\0' - first = last - -proc splitLines*(s: string): seq[string] {.noSideEffect, - rtl, extern: "nsuSplitLines".} = - ## The same as the `splitLines` iterator, but is a proc that returns a - ## sequence of substrings. - accumulateResult(splitLines(s)) - -proc countLines*(s: string): int {.noSideEffect, - rtl, extern: "nsuCountLines".} = - ## same as ``len(splitLines(s))``, but much more efficient. - var i = 0 - while i < s.len: - case s[i] - of '\c': - if s[i+1] == '\l': inc i - inc result - of '\l': inc result - else: nil - inc i - -proc split*(s: string, seps: set[char] = Whitespace): seq[string] {. - noSideEffect, rtl, extern: "nsuSplitCharSet".} = - ## The same as the `split` iterator, but is a proc that returns a - ## sequence of substrings. - accumulateResult(split(s, seps)) - -proc split*(s: string, sep: char): seq[string] {.noSideEffect, - rtl, extern: "nsuSplitChar".} = - ## The same as the `split` iterator, but is a proc that returns a sequence - ## of substrings. - accumulateResult(split(s, sep)) - -proc toHex*(x: BiggestInt, len: int): string {.noSideEffect, - rtl, extern: "nsuToHex".} = - ## Converts `x` to its hexadecimal representation. The resulting string - ## will be exactly `len` characters long. No prefix like ``0x`` - ## is generated. `x` is treated as an unsigned value. - const - HexChars = "0123456789ABCDEF" - var - shift: BiggestInt - result = newString(len) - for j in countdown(len-1, 0): - result[j] = HexChars[toU32(x shr shift) and 0xF'i32] - shift = shift + 4 - -proc intToStr*(x: int, minchars: int = 1): string {.noSideEffect, - rtl, extern: "nsuIntToStr".} = - ## Converts `x` to its decimal representation. The resulting string - ## will be minimally `minchars` characters long. This is achieved by - ## adding leading zeros. - result = $abs(x) - for i in 1 .. minchars - len(result): - result = '0' & result - if x < 0: - result = '-' & result - -proc parseInt*(s: string): int {.noSideEffect, procvar, - rtl, extern: "nsuParseInt".} = - ## Parses a decimal integer value contained in `s`. If `s` is not - ## a valid integer, `EInvalidValue` is raised. - var L = parseutils.parseInt(s, result, 0) - if L != s.len or L == 0: - raise newException(EInvalidValue, "invalid integer: " & s) - -proc parseBiggestInt*(s: string): biggestInt {.noSideEffect, procvar, - rtl, extern: "nsuParseBiggestInt".} = - ## Parses a decimal integer value contained in `s`. If `s` is not - ## a valid integer, `EInvalidValue` is raised. - var L = parseutils.parseBiggestInt(s, result, 0) - if L != s.len or L == 0: - raise newException(EInvalidValue, "invalid integer: " & s) - -proc parseFloat*(s: string): float {.noSideEffect, procvar, - rtl, extern: "nsuParseFloat".} = - ## Parses a decimal floating point value contained in `s`. If `s` is not - ## a valid floating point number, `EInvalidValue` is raised. ``NAN``, - ## ``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) - -proc parseHexInt*(s: string): int {.noSideEffect, procvar, - rtl, extern: "nsuParseHexInt".} = - ## Parses a hexadecimal integer value contained in `s`. If `s` is not - ## a valid integer, `EInvalidValue` is raised. `s` can have one of the - ## following optional prefixes: ``0x``, ``0X``, ``#``. - ## Underscores within `s` are ignored. - var i = 0 - if s[i] == '0' and (s[i+1] == 'x' or s[i+1] == 'X'): inc(i, 2) - elif s[i] == '#': inc(i) - while true: - case s[i] - of '_': inc(i) - of '0'..'9': - result = result shl 4 or (ord(s[i]) - ord('0')) - inc(i) - of 'a'..'f': - result = result shl 4 or (ord(s[i]) - ord('a') + 10) - inc(i) - of 'A'..'F': - result = result shl 4 or (ord(s[i]) - ord('A') + 10) - inc(i) - of '\0': break - else: raise newException(EInvalidValue, "invalid integer: " & s) - -proc parseBool*(s: string): bool = - ## Parses a value into a `bool`. If ``s`` is one of the following values: - ## ``y, yes, true, 1, on``, then returns `true`. If ``s`` is one of the - ## following values: ``n, no, false, 0, off``, then returns `false`. - ## If ``s`` is something else a ``EInvalidValue`` exception is raised. - 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) + var last = 0 + assert(not ('\0' in seps)) + while last < len(s): + while s[last] in seps: inc(last) + var first = last + while last < len(s) and s[last] not_in seps: inc(last) # BUGFIX! + if first <= last-1: + yield substr(s, first, last-1) + +iterator split*(s: string, sep: char): string = + ## Splits the string `s` into substrings using a single separator. + ## + ## Substrings are separated by the character `sep`. + ## Unlike the version of the iterator which accepts a set of separator + ## characters, this proc will not coalesce groups of the + ## separator, returning a string for each found character. The code: + ## + ## .. code-block:: nimrod + ## for word in split(";;this;is;an;;example;;;", ';'): + ## writeln(stdout, word) + ## + ## Results in: + ## + ## .. code-block:: + ## "" + ## "" + ## "this" + ## "is" + ## "an" + ## "" + ## "example" + ## "" + ## "" + ## "" + ## + var last = 0 + assert('\0' != sep) + if len(s) > 0: + # `<=` is correct here for the edge cases! + while last <= len(s): + var first = last + while last < len(s) and s[last] != sep: inc(last) + yield substr(s, first, last-1) + inc(last) + +iterator splitLines*(s: string): string = + ## Splits the string `s` into its containing lines. Every newline + ## combination (CR, LF, CR-LF) is supported. The result strings contain + ## no trailing ``\n``. + ## + ## Example: + ## + ## .. code-block:: nimrod + ## for line in splitLines("\nthis\nis\nan\n\nexample\n"): + ## writeln(stdout, line) + ## + ## Results in: + ## + ## .. code-block:: nimrod + ## "" + ## "this" + ## "is" + ## "an" + ## "" + ## "example" + ## "" + var first = 0 + var last = 0 + while true: + while s[last] notin {'\0', '\c', '\l'}: inc(last) + yield substr(s, first, last-1) + # skip newlines: + if s[last] == '\l': inc(last) + elif s[last] == '\c': + inc(last) + if s[last] == '\l': inc(last) + else: break # was '\0' + first = last + +proc splitLines*(s: string): seq[string] {.noSideEffect, + rtl, extern: "nsuSplitLines".} = + ## The same as the `splitLines` iterator, but is a proc that returns a + ## sequence of substrings. + accumulateResult(splitLines(s)) + +proc countLines*(s: string): int {.noSideEffect, + rtl, extern: "nsuCountLines".} = + ## same as ``len(splitLines(s))``, but much more efficient. + var i = 0 + while i < s.len: + case s[i] + of '\c': + if s[i+1] == '\l': inc i + inc result + of '\l': inc result + else: nil + inc i + +proc split*(s: string, seps: set[char] = Whitespace): seq[string] {. + noSideEffect, rtl, extern: "nsuSplitCharSet".} = + ## The same as the `split` iterator, but is a proc that returns a + ## sequence of substrings. + accumulateResult(split(s, seps)) + +proc split*(s: string, sep: char): seq[string] {.noSideEffect, + rtl, extern: "nsuSplitChar".} = + ## The same as the `split` iterator, but is a proc that returns a sequence + ## of substrings. + accumulateResult(split(s, sep)) + +proc toHex*(x: BiggestInt, len: int): string {.noSideEffect, + rtl, extern: "nsuToHex".} = + ## Converts `x` to its hexadecimal representation. The resulting string + ## will be exactly `len` characters long. No prefix like ``0x`` + ## is generated. `x` is treated as an unsigned value. + const + HexChars = "0123456789ABCDEF" + var + shift: BiggestInt + result = newString(len) + for j in countdown(len-1, 0): + result[j] = HexChars[toU32(x shr shift) and 0xF'i32] + shift = shift + 4 + +proc intToStr*(x: int, minchars: int = 1): string {.noSideEffect, + rtl, extern: "nsuIntToStr".} = + ## Converts `x` to its decimal representation. The resulting string + ## will be minimally `minchars` characters long. This is achieved by + ## adding leading zeros. + result = $abs(x) + for i in 1 .. minchars - len(result): + result = '0' & result + if x < 0: + result = '-' & result + +proc parseInt*(s: string): int {.noSideEffect, procvar, + rtl, extern: "nsuParseInt".} = + ## Parses a decimal integer value contained in `s`. If `s` is not + ## a valid integer, `EInvalidValue` is raised. + var L = parseutils.parseInt(s, result, 0) + if L != s.len or L == 0: + raise newException(EInvalidValue, "invalid integer: " & s) + +proc parseBiggestInt*(s: string): BiggestInt {.noSideEffect, procvar, + rtl, extern: "nsuParseBiggestInt".} = + ## Parses a decimal integer value contained in `s`. If `s` is not + ## a valid integer, `EInvalidValue` is raised. + var L = parseutils.parseBiggestInt(s, result, 0) + if L != s.len or L == 0: + raise newException(EInvalidValue, "invalid integer: " & s) + +proc parseFloat*(s: string): float {.noSideEffect, procvar, + rtl, extern: "nsuParseFloat".} = + ## Parses a decimal floating point value contained in `s`. If `s` is not + ## a valid floating point number, `EInvalidValue` is raised. ``NAN``, + ## ``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) + +proc parseHexInt*(s: string): int {.noSideEffect, procvar, + rtl, extern: "nsuParseHexInt".} = + ## Parses a hexadecimal integer value contained in `s`. If `s` is not + ## a valid integer, `EInvalidValue` is raised. `s` can have one of the + ## following optional prefixes: ``0x``, ``0X``, ``#``. + ## Underscores within `s` are ignored. + var i = 0 + if s[i] == '0' and (s[i+1] == 'x' or s[i+1] == 'X'): inc(i, 2) + elif s[i] == '#': inc(i) + while true: + case s[i] + of '_': inc(i) + of '0'..'9': + result = result shl 4 or (ord(s[i]) - ord('0')) + inc(i) + of 'a'..'f': + result = result shl 4 or (ord(s[i]) - ord('a') + 10) + inc(i) + of 'A'..'F': + result = result shl 4 or (ord(s[i]) - ord('A') + 10) + inc(i) + of '\0': break + else: raise newException(EInvalidValue, "invalid integer: " & s) + +proc parseBool*(s: string): bool = + ## Parses a value into a `bool`. If ``s`` is one of the following values: + ## ``y, yes, true, 1, on``, then returns `true`. If ``s`` is one of the + ## following values: ``n, no, false, 0, off``, then returns `false`. + ## If ``s`` is something else a ``EInvalidValue`` exception is raised. + 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) proc parseEnum*[T: enum](s: string): T = ## parses an enum ``T``. Raises ``EInvalidValue`` for an invalid value in @@ -418,30 +418,30 @@ proc parseEnum*[T: enum](s: string, default: T): T = if cmpIgnoreStyle(s, $e) == 0: return e result = default - -proc repeatChar*(count: int, c: Char = ' '): string {.noSideEffect, - rtl, extern: "nsuRepeatChar".} = - ## Returns a string of length `count` consisting only of - ## the character `c`. You can use this proc to left align strings. Example: - ## - ## .. code-block:: nimrod - ## let - ## width = 15 - ## text1 = "Hello user!" - ## text2 = "This is a very long string" - ## echo text1 & repeatChar(max(0, width - text1.len)) & "|" - ## echo text2 & repeatChar(max(0, width - text2.len)) & "|" - result = newString(count) - for i in 0..count-1: result[i] = c - -proc repeatStr*(count: int, s: string): string {.noSideEffect, - rtl, extern: "nsuRepeatStr".} = - ## Returns `s` concatenated `count` times. - result = newStringOfCap(count*s.len) - for i in 0..count-1: result.add(s) - -proc align*(s: string, count: int, padding = ' '): string {. - noSideEffect, rtl, extern: "nsuAlignString".} = + +proc repeatChar*(count: int, c: char = ' '): string {.noSideEffect, + rtl, extern: "nsuRepeatChar".} = + ## Returns a string of length `count` consisting only of + ## the character `c`. You can use this proc to left align strings. Example: + ## + ## .. code-block:: nimrod + ## let + ## width = 15 + ## text1 = "Hello user!" + ## text2 = "This is a very long string" + ## echo text1 & repeatChar(max(0, width - text1.len)) & "|" + ## echo text2 & repeatChar(max(0, width - text2.len)) & "|" + result = newString(count) + for i in 0..count-1: result[i] = c + +proc repeatStr*(count: int, s: string): string {.noSideEffect, + rtl, extern: "nsuRepeatStr".} = + ## Returns `s` concatenated `count` times. + result = newStringOfCap(count*s.len) + for i in 0..count-1: result.add(s) + +proc align*(s: string, count: int, padding = ' '): string {. + noSideEffect, rtl, extern: "nsuAlignString".} = ## Aligns a string `s` with `padding`, so that is of length `count`. ## `padding` characters (by default spaces) are added before `s` resulting in ## right alignment. If ``s.len >= count``, no spaces are added and `s` is @@ -453,247 +453,247 @@ proc align*(s: string, count: int, padding = ' '): string {. ## assert align("a", 0) == "a" ## assert align("1232", 6) == " 1232" ## assert align("1232", 6, '#') == "##1232" - if s.len < count: - result = newString(count) - let spaces = count - s.len - for i in 0..spaces-1: result[i] = padding - for i in spaces..count-1: result[i] = s[i-spaces] - else: - result = s - -iterator tokenize*(s: string, seps: set[char] = Whitespace): tuple[ - token: string, isSep: bool] = - ## Tokenizes the string `s` into substrings. - ## - ## Substrings are separated by a substring containing only `seps`. - ## Examples: - ## - ## .. code-block:: nimrod - ## for word in tokenize(" this is an example "): - ## writeln(stdout, word) - ## - ## Results in: - ## - ## .. code-block:: nimrod - ## (" ", true) - ## ("this", false) - ## (" ", true) - ## ("is", false) - ## (" ", true) - ## ("an", false) - ## (" ", true) - ## ("example", false) - ## (" ", true) - var i = 0 - while true: - var j = i - var isSep = s[j] in seps - while j < s.len and (s[j] in seps) == isSep: inc(j) - if j > i: - yield (substr(s, i, j-1), isSep) - else: - break - i = j - -proc wordWrap*(s: string, maxLineWidth = 80, - splitLongWords = true, - seps: set[char] = whitespace, - newLine = "\n"): string {. - noSideEffect, rtl, extern: "nsuWordWrap".} = - ## word wraps `s`. - result = newStringOfCap(s.len + s.len shr 6) - var SpaceLeft = maxLineWidth - for word, isSep in tokenize(s, seps): - if len(word) > SpaceLeft: - if splitLongWords and len(word) > maxLineWidth: - result.add(substr(word, 0, spaceLeft-1)) - var w = spaceLeft+1 - var wordLeft = len(word) - spaceLeft - while wordLeft > 0: - result.add(newLine) - var L = min(maxLineWidth, wordLeft) - SpaceLeft = maxLineWidth - L - result.add(substr(word, w, w+L-1)) - inc(w, L) - dec(wordLeft, L) - else: - SpaceLeft = maxLineWidth - len(Word) - result.add(newLine) - result.add(word) - else: - SpaceLeft = SpaceLeft - len(Word) - result.add(word) - -proc unindent*(s: string, eatAllIndent = false): string {. - noSideEffect, rtl, extern: "nsuUnindent".} = - ## unindents `s`. - result = newStringOfCap(s.len) - var i = 0 - var pattern = true - var indent = 0 - while s[i] == ' ': inc i - var level = if i == 0: -1 else: i - while i < s.len: - if s[i] == ' ': - if i > 0 and s[i-1] in {'\l', '\c'}: - pattern = true - indent = 0 - if pattern: - inc(indent) - if indent > level and not eatAllIndent: - result.add(s[i]) - if level < 0: level = indent - else: - # a space somewhere: do not delete - result.add(s[i]) - else: - pattern = false - result.add(s[i]) - inc i - -proc startsWith*(s, prefix: string): bool {.noSideEffect, - rtl, extern: "nsuStartsWith".} = - ## Returns true iff ``s`` starts with ``prefix``. - ## If ``prefix == ""`` true is returned. - var i = 0 - while true: - if prefix[i] == '\0': return true - if s[i] != prefix[i]: return false - inc(i) - -proc endsWith*(s, suffix: string): bool {.noSideEffect, - rtl, extern: "nsuEndsWith".} = - ## Returns true iff ``s`` ends with ``suffix``. - ## If ``suffix == ""`` true is returned. - var i = 0 - var j = len(s) - len(suffix) - while i+j <% s.len: - if s[i+j] != suffix[i]: return false - inc(i) - if suffix[i] == '\0': return true + if s.len < count: + result = newString(count) + let spaces = count - s.len + for i in 0..spaces-1: result[i] = padding + for i in spaces..count-1: result[i] = s[i-spaces] + else: + result = s + +iterator tokenize*(s: string, seps: set[char] = Whitespace): tuple[ + token: string, isSep: bool] = + ## Tokenizes the string `s` into substrings. + ## + ## Substrings are separated by a substring containing only `seps`. + ## Examples: + ## + ## .. code-block:: nimrod + ## for word in tokenize(" this is an example "): + ## writeln(stdout, word) + ## + ## Results in: + ## + ## .. code-block:: nimrod + ## (" ", true) + ## ("this", false) + ## (" ", true) + ## ("is", false) + ## (" ", true) + ## ("an", false) + ## (" ", true) + ## ("example", false) + ## (" ", true) + var i = 0 + while true: + var j = i + var isSep = s[j] in seps + while j < s.len and (s[j] in seps) == isSep: inc(j) + if j > i: + yield (substr(s, i, j-1), isSep) + else: + break + i = j + +proc wordWrap*(s: string, maxLineWidth = 80, + splitLongWords = true, + seps: set[char] = whitespace, + newLine = "\n"): string {. + noSideEffect, rtl, extern: "nsuWordWrap".} = + ## word wraps `s`. + result = newStringOfCap(s.len + s.len shr 6) + var SpaceLeft = maxLineWidth + for word, isSep in tokenize(s, seps): + if len(word) > SpaceLeft: + if splitLongWords and len(word) > maxLineWidth: + result.add(substr(word, 0, SpaceLeft-1)) + var w = SpaceLeft+1 + var wordLeft = len(word) - SpaceLeft + while wordLeft > 0: + result.add(newLine) + var L = min(maxLineWidth, wordLeft) + SpaceLeft = maxLineWidth - L + result.add(substr(word, w, w+L-1)) + inc(w, L) + dec(wordLeft, L) + else: + SpaceLeft = maxLineWidth - len(word) + result.add(newLine) + result.add(word) + else: + SpaceLeft = SpaceLeft - len(word) + result.add(word) + +proc unindent*(s: string, eatAllIndent = false): string {. + noSideEffect, rtl, extern: "nsuUnindent".} = + ## unindents `s`. + result = newStringOfCap(s.len) + var i = 0 + var pattern = true + var indent = 0 + while s[i] == ' ': inc i + var level = if i == 0: -1 else: i + while i < s.len: + if s[i] == ' ': + if i > 0 and s[i-1] in {'\l', '\c'}: + pattern = true + indent = 0 + if pattern: + inc(indent) + if indent > level and not eatAllIndent: + result.add(s[i]) + if level < 0: level = indent + else: + # a space somewhere: do not delete + result.add(s[i]) + else: + pattern = false + result.add(s[i]) + inc i + +proc startsWith*(s, prefix: string): bool {.noSideEffect, + rtl, extern: "nsuStartsWith".} = + ## Returns true iff ``s`` starts with ``prefix``. + ## If ``prefix == ""`` true is returned. + var i = 0 + while true: + if prefix[i] == '\0': return true + if s[i] != prefix[i]: return false + inc(i) + +proc endsWith*(s, suffix: string): bool {.noSideEffect, + rtl, extern: "nsuEndsWith".} = + ## Returns true iff ``s`` ends with ``suffix``. + ## If ``suffix == ""`` true is returned. + var i = 0 + var j = len(s) - len(suffix) + while i+j <% s.len: + if s[i+j] != suffix[i]: return false + inc(i) + if suffix[i] == '\0': return true proc continuesWith*(s, substr: string, start: int): bool {.noSideEffect, rtl, extern: "nsuContinuesWith".} = - ## Returns true iff ``s`` continues with ``substr`` at position ``start``. - ## If ``substr == ""`` true is returned. - var i = 0 - while true: - if substr[i] == '\0': return true - if s[i+start] != substr[i]: return false - inc(i) - -proc addSep*(dest: var string, sep = ", ", startLen = 0) {.noSideEffect, - inline.} = - ## A shorthand for: - ## - ## .. code-block:: nimrod - ## if dest.len > startLen: add(dest, sep) - ## - ## This is often useful for generating some code where the items need to - ## be *separated* by `sep`. `sep` is only added if `dest` is longer than - ## `startLen`. The following example creates a string describing - ## an array of integers: - ## - ## .. code-block:: nimrod - ## var arr = "[" - ## for x in items([2, 3, 5, 7, 11]): - ## addSep(arr, startLen=len("[")) - ## add(arr, $x) - ## add(arr, "]") - if dest.len > startLen: add(dest, sep) - -proc allCharsInSet*(s: string, theSet: TCharSet): bool = - ## returns true iff each character of `s` is in the set `theSet`. - for c in items(s): - if c notin theSet: return false - return true - -proc abbrev*(s: string, possibilities: openarray[string]): int = - ## returns the index of the first item in `possibilities` if not - ## ambiguous; -1 if no item has been found; -2 if multiple items - ## match. - result = -1 # none found - for i in 0..possibilities.len-1: - if possibilities[i].startsWith(s): - if possibilities[i] == s: - # special case: exact match shouldn't be ambiguous - return i - if result >= 0: return -2 # ambiguous - result = i - -# --------------------------------------------------------------------------- - -proc join*(a: openArray[string], sep: string): string {. - noSideEffect, rtl, extern: "nsuJoinSep".} = - ## concatenates all strings in `a` separating them with `sep`. - if len(a) > 0: - var L = sep.len * (a.len-1) - for i in 0..high(a): inc(L, a[i].len) - result = newStringOfCap(L) - add(result, a[0]) - for i in 1..high(a): - add(result, sep) - add(result, a[i]) - else: - result = "" - -proc join*(a: openArray[string]): string {. - noSideEffect, rtl, extern: "nsuJoin".} = - ## concatenates all strings in `a`. - if len(a) > 0: - var L = 0 - for i in 0..high(a): inc(L, a[i].len) - result = newStringOfCap(L) - for i in 0..high(a): add(result, a[i]) - else: - result = "" - -type - TSkipTable = array[char, int] - -proc preprocessSub(sub: string, a: var TSkipTable) = - var m = len(sub) - for i in 0..0xff: a[chr(i)] = m+1 - for i in 0..m-1: a[sub[i]] = m-i - -proc findAux(s, sub: string, start: int, a: TSkipTable): int = - # fast "quick search" algorithm: - var - m = len(sub) - n = len(s) - # search: - var j = start - while j <= n - m: - block match: - for k in 0..m-1: - if sub[k] != s[k+j]: break match - return j - inc(j, a[s[j+m]]) - return -1 - -proc find*(s, sub: string, start: int = 0): int {.noSideEffect, - rtl, extern: "nsuFindStr", operator: 6.} = - ## Searches for `sub` in `s` starting at position `start`. Searching is - ## case-sensitive. If `sub` is not in `s`, -1 is returned. - var a {.noinit.}: TSkipTable - preprocessSub(sub, a) - result = findAux(s, sub, start, a) - -proc find*(s: string, sub: char, start: int = 0): int {.noSideEffect, - rtl, extern: "nsuFindChar".} = - ## Searches for `sub` in `s` starting at position `start`. Searching is - ## case-sensitive. If `sub` is not in `s`, -1 is returned. - for i in start..len(s)-1: - if sub == s[i]: return i - return -1 - -proc find*(s: string, chars: set[char], start: int = 0): int {.noSideEffect, - rtl, extern: "nsuFindCharSet".} = - ## Searches for `chars` in `s` starting at position `start`. If `s` contains - ## none of the characters in `chars`, -1 is returned. - for i in start..s.len-1: - if s[i] in chars: return i - return -1 + ## Returns true iff ``s`` continues with ``substr`` at position ``start``. + ## If ``substr == ""`` true is returned. + var i = 0 + while true: + if substr[i] == '\0': return true + if s[i+start] != substr[i]: return false + inc(i) + +proc addSep*(dest: var string, sep = ", ", startLen = 0) {.noSideEffect, + inline.} = + ## A shorthand for: + ## + ## .. code-block:: nimrod + ## if dest.len > startLen: add(dest, sep) + ## + ## This is often useful for generating some code where the items need to + ## be *separated* by `sep`. `sep` is only added if `dest` is longer than + ## `startLen`. The following example creates a string describing + ## an array of integers: + ## + ## .. code-block:: nimrod + ## var arr = "[" + ## for x in items([2, 3, 5, 7, 11]): + ## addSep(arr, startLen=len("[")) + ## add(arr, $x) + ## add(arr, "]") + if dest.len > startLen: add(dest, sep) + +proc allCharsInSet*(s: string, theSet: TCharSet): bool = + ## returns true iff each character of `s` is in the set `theSet`. + for c in items(s): + if c notin theSet: return false + return true + +proc abbrev*(s: string, possibilities: openArray[string]): int = + ## returns the index of the first item in `possibilities` if not + ## ambiguous; -1 if no item has been found; -2 if multiple items + ## match. + result = -1 # none found + for i in 0..possibilities.len-1: + if possibilities[i].startsWith(s): + if possibilities[i] == s: + # special case: exact match shouldn't be ambiguous + return i + if result >= 0: return -2 # ambiguous + result = i + +# --------------------------------------------------------------------------- + +proc join*(a: openArray[string], sep: string): string {. + noSideEffect, rtl, extern: "nsuJoinSep".} = + ## concatenates all strings in `a` separating them with `sep`. + if len(a) > 0: + var L = sep.len * (a.len-1) + for i in 0..high(a): inc(L, a[i].len) + result = newStringOfCap(L) + add(result, a[0]) + for i in 1..high(a): + add(result, sep) + add(result, a[i]) + else: + result = "" + +proc join*(a: openArray[string]): string {. + noSideEffect, rtl, extern: "nsuJoin".} = + ## concatenates all strings in `a`. + if len(a) > 0: + var L = 0 + for i in 0..high(a): inc(L, a[i].len) + result = newStringOfCap(L) + for i in 0..high(a): add(result, a[i]) + else: + result = "" + +type + TSkipTable = array[char, int] + +proc preprocessSub(sub: string, a: var TSkipTable) = + var m = len(sub) + for i in 0..0xff: a[chr(i)] = m+1 + for i in 0..m-1: a[sub[i]] = m-i + +proc findAux(s, sub: string, start: int, a: TSkipTable): int = + # fast "quick search" algorithm: + var + m = len(sub) + n = len(s) + # search: + var j = start + while j <= n - m: + block match: + for k in 0..m-1: + if sub[k] != s[k+j]: break match + return j + inc(j, a[s[j+m]]) + return -1 + +proc find*(s, sub: string, start: int = 0): int {.noSideEffect, + rtl, extern: "nsuFindStr", operator: 6.} = + ## Searches for `sub` in `s` starting at position `start`. Searching is + ## case-sensitive. If `sub` is not in `s`, -1 is returned. + var a {.noinit.}: TSkipTable + preprocessSub(sub, a) + result = findAux(s, sub, start, a) + +proc find*(s: string, sub: char, start: int = 0): int {.noSideEffect, + rtl, extern: "nsuFindChar".} = + ## Searches for `sub` in `s` starting at position `start`. Searching is + ## case-sensitive. If `sub` is not in `s`, -1 is returned. + for i in start..len(s)-1: + if sub == s[i]: return i + return -1 + +proc find*(s: string, chars: set[char], start: int = 0): int {.noSideEffect, + rtl, extern: "nsuFindCharSet".} = + ## Searches for `chars` in `s` starting at position `start`. If `s` contains + ## none of the characters in `chars`, -1 is returned. + for i in start..s.len-1: + if s[i] in chars: return i + return -1 proc rfind*(s, sub: string, start: int = -1): int {.noSideEffect.} = ## Searches for `sub` in `s` in reverse, starting at `start` and going @@ -708,180 +708,180 @@ proc rfind*(s, sub: string, start: int = -1): int {.noSideEffect.} = break if result != -1: return return -1 - + proc quoteIfContainsWhite*(s: string): string {.deprecated.} = - ## returns ``'"' & s & '"'`` if `s` contains a space and does not - ## start with a quote, else returns `s` + ## returns ``'"' & s & '"'`` if `s` contains a space and does not + ## start with a quote, else returns `s` ## DEPRECATED as it was confused for shell quoting function. ## For this application use osproc.quoteShell. - if find(s, {' ', '\t'}) >= 0 and s[0] != '"': - result = '"' & s & '"' - else: - result = s - -proc contains*(s: string, c: char): bool {.noSideEffect.} = - ## Same as ``find(s, c) >= 0``. - return find(s, c) >= 0 - -proc contains*(s, sub: string): bool {.noSideEffect.} = - ## Same as ``find(s, sub) >= 0``. - return find(s, sub) >= 0 - -proc contains*(s: string, chars: set[char]): bool {.noSideEffect.} = - ## Same as ``find(s, chars) >= 0``. - return find(s, chars) >= 0 - -proc replace*(s, sub: string, by = ""): string {.noSideEffect, - rtl, extern: "nsuReplaceStr", operator: 1.} = - ## Replaces `sub` in `s` by the string `by`. - var a {.noinit.}: TSkipTable - result = "" - preprocessSub(sub, a) - var i = 0 - while true: - var j = findAux(s, sub, i, a) - if j < 0: break - add result, substr(s, i, j - 1) - add result, by - i = j + len(sub) - # copy the rest: - add result, substr(s, i) - -proc replace*(s: string, sub, by: char): string {.noSideEffect, - rtl, extern: "nsuReplaceChar".} = - ## optimized version for characters. - result = newString(s.len) - var i = 0 - while i < s.len: - if s[i] == sub: result[i] = by - else: result[i] = s[i] - inc(i) - -proc replaceWord*(s, sub: string, by = ""): string {.noSideEffect, - rtl, extern: "nsuReplaceWord".} = - ## Replaces `sub` in `s` by the string `by`. Each occurance of `sub` - ## has to be surrounded by word boundaries (comparable to ``\\w`` in - ## regular expressions), otherwise it is not replaced. - const wordChars = {'a'..'z', 'A'..'Z', '0'..'9', '_', '\128'..'\255'} - var a {.noinit.}: TSkipTable - result = "" - preprocessSub(sub, a) - var i = 0 - while true: - var j = findAux(s, sub, i, a) - if j < 0: break - # word boundary? - if (j == 0 or s[j-1] notin wordChars) and - (j+sub.len >= s.len or s[j+sub.len] notin wordChars): - add result, substr(s, i, j - 1) - add result, by - i = j + len(sub) - else: - add result, substr(s, i, j) - i = j + 1 - # copy the rest: - add result, substr(s, i) - -proc delete*(s: var string, first, last: int) {.noSideEffect, - rtl, extern: "nsuDelete".} = - ## Deletes in `s` the characters at position `first` .. `last`. This modifies - ## `s` itself, it does not return a copy. - var i = first - var j = last+1 - var newLen = len(s)-j+i - while i < newLen: - s[i] = s[j] - inc(i) - inc(j) - setlen(s, newLen) - -proc parseOctInt*(s: string): int {.noSideEffect, - rtl, extern: "nsuParseOctInt".} = - ## Parses an octal integer value contained in `s`. If `s` is not - ## a valid integer, `EInvalidValue` is raised. `s` can have one of the - ## following optional prefixes: ``0o``, ``0O``. - ## Underscores within `s` are ignored. - var i = 0 - if s[i] == '0' and (s[i+1] == 'o' or s[i+1] == 'O'): inc(i, 2) - while true: - case s[i] - of '_': inc(i) - of '0'..'7': - result = result shl 3 or (ord(s[i]) - ord('0')) - inc(i) - of '\0': break - else: raise newException(EInvalidValue, "invalid integer: " & s) - -proc toOct*(x: BiggestInt, len: int): string {.noSideEffect, - rtl, extern: "nsuToOct".} = - ## converts `x` into its octal representation. The resulting string is - ## always `len` characters long. No leading ``0o`` prefix is generated. - var - mask: BiggestInt = 7 - shift: BiggestInt = 0 - assert(len > 0) - result = newString(len) - for j in countdown(len-1, 0): - result[j] = chr(int((x and mask) shr shift) + ord('0')) - shift = shift + 3 - mask = mask shl 3 - -proc toBin*(x: BiggestInt, len: int): string {.noSideEffect, - rtl, extern: "nsuToBin".} = - ## converts `x` into its binary representation. The resulting string is - ## always `len` characters long. No leading ``0b`` prefix is generated. - var - mask: BiggestInt = 1 - shift: BiggestInt = 0 - assert(len > 0) - result = newString(len) - for j in countdown(len-1, 0): - result[j] = chr(int((x and mask) shr shift) + ord('0')) - shift = shift + 1 - mask = mask shl 1 - -proc insertSep*(s: string, sep = '_', digits = 3): string {.noSideEffect, - rtl, extern: "nsuInsertSep".} = - ## inserts the separator `sep` after `digits` digits from right to left. - ## Even though the algorithm works with any string `s`, it is only useful - ## if `s` contains a number. - ## Example: ``insertSep("1000000") == "1_000_000"`` - var L = (s.len-1) div digits + s.len - result = newString(L) - var j = 0 - dec(L) - for i in countdown(len(s)-1, 0): - if j == digits: - result[L] = sep - dec(L) - j = 0 - result[L] = s[i] - inc(j) - dec(L) - -proc escape*(s: string, prefix = "\"", suffix = "\""): string {.noSideEffect, - rtl, extern: "nsuEscape".} = - ## Escapes a string `s`. This does these operations (at the same time): - ## * replaces any ``\`` by ``\\`` - ## * replaces any ``'`` by ``\'`` - ## * replaces any ``"`` by ``\"`` - ## * replaces any other character in the set ``{'\0'..'\31', '\128'..'\255'}`` - ## by ``\xHH`` where ``HH`` is its hexadecimal value. - ## The procedure has been designed so that its output is usable for many - ## different common syntaxes. The resulting string is prefixed with - ## `prefix` and suffixed with `suffix`. Both may be empty strings. - result = newStringOfCap(s.len + s.len shr 2) - result.add(prefix) - for c in items(s): - case c - of '\0'..'\31', '\128'..'\255': - add(result, "\\x") - add(result, toHex(ord(c), 2)) - of '\\': add(result, "\\\\") - of '\'': add(result, "\\'") - of '\"': add(result, "\\\"") - else: add(result, c) - add(result, suffix) + if find(s, {' ', '\t'}) >= 0 and s[0] != '"': + result = '"' & s & '"' + else: + result = s + +proc contains*(s: string, c: char): bool {.noSideEffect.} = + ## Same as ``find(s, c) >= 0``. + return find(s, c) >= 0 + +proc contains*(s, sub: string): bool {.noSideEffect.} = + ## Same as ``find(s, sub) >= 0``. + return find(s, sub) >= 0 + +proc contains*(s: string, chars: set[char]): bool {.noSideEffect.} = + ## Same as ``find(s, chars) >= 0``. + return find(s, chars) >= 0 + +proc replace*(s, sub: string, by = ""): string {.noSideEffect, + rtl, extern: "nsuReplaceStr", operator: 1.} = + ## Replaces `sub` in `s` by the string `by`. + var a {.noinit.}: TSkipTable + result = "" + preprocessSub(sub, a) + var i = 0 + while true: + var j = findAux(s, sub, i, a) + if j < 0: break + add result, substr(s, i, j - 1) + add result, by + i = j + len(sub) + # copy the rest: + add result, substr(s, i) + +proc replace*(s: string, sub, by: char): string {.noSideEffect, + rtl, extern: "nsuReplaceChar".} = + ## optimized version for characters. + result = newString(s.len) + var i = 0 + while i < s.len: + if s[i] == sub: result[i] = by + else: result[i] = s[i] + inc(i) + +proc replaceWord*(s, sub: string, by = ""): string {.noSideEffect, + rtl, extern: "nsuReplaceWord".} = + ## Replaces `sub` in `s` by the string `by`. Each occurance of `sub` + ## has to be surrounded by word boundaries (comparable to ``\\w`` in + ## regular expressions), otherwise it is not replaced. + const wordChars = {'a'..'z', 'A'..'Z', '0'..'9', '_', '\128'..'\255'} + var a {.noinit.}: TSkipTable + result = "" + preprocessSub(sub, a) + var i = 0 + while true: + var j = findAux(s, sub, i, a) + if j < 0: break + # word boundary? + if (j == 0 or s[j-1] notin wordChars) and + (j+sub.len >= s.len or s[j+sub.len] notin wordChars): + add result, substr(s, i, j - 1) + add result, by + i = j + len(sub) + else: + add result, substr(s, i, j) + i = j + 1 + # copy the rest: + add result, substr(s, i) + +proc delete*(s: var string, first, last: int) {.noSideEffect, + rtl, extern: "nsuDelete".} = + ## Deletes in `s` the characters at position `first` .. `last`. This modifies + ## `s` itself, it does not return a copy. + var i = first + var j = last+1 + var newLen = len(s)-j+i + while i < newLen: + s[i] = s[j] + inc(i) + inc(j) + setLen(s, newLen) + +proc parseOctInt*(s: string): int {.noSideEffect, + rtl, extern: "nsuParseOctInt".} = + ## Parses an octal integer value contained in `s`. If `s` is not + ## a valid integer, `EInvalidValue` is raised. `s` can have one of the + ## following optional prefixes: ``0o``, ``0O``. + ## Underscores within `s` are ignored. + var i = 0 + if s[i] == '0' and (s[i+1] == 'o' or s[i+1] == 'O'): inc(i, 2) + while true: + case s[i] + of '_': inc(i) + of '0'..'7': + result = result shl 3 or (ord(s[i]) - ord('0')) + inc(i) + of '\0': break + else: raise newException(EInvalidValue, "invalid integer: " & s) + +proc toOct*(x: BiggestInt, len: int): string {.noSideEffect, + rtl, extern: "nsuToOct".} = + ## converts `x` into its octal representation. The resulting string is + ## always `len` characters long. No leading ``0o`` prefix is generated. + var + mask: BiggestInt = 7 + shift: BiggestInt = 0 + assert(len > 0) + result = newString(len) + for j in countdown(len-1, 0): + result[j] = chr(int((x and mask) shr shift) + ord('0')) + shift = shift + 3 + mask = mask shl 3 + +proc toBin*(x: BiggestInt, len: int): string {.noSideEffect, + rtl, extern: "nsuToBin".} = + ## converts `x` into its binary representation. The resulting string is + ## always `len` characters long. No leading ``0b`` prefix is generated. + var + mask: BiggestInt = 1 + shift: BiggestInt = 0 + assert(len > 0) + result = newString(len) + for j in countdown(len-1, 0): + result[j] = chr(int((x and mask) shr shift) + ord('0')) + shift = shift + 1 + mask = mask shl 1 + +proc insertSep*(s: string, sep = '_', digits = 3): string {.noSideEffect, + rtl, extern: "nsuInsertSep".} = + ## inserts the separator `sep` after `digits` digits from right to left. + ## Even though the algorithm works with any string `s`, it is only useful + ## if `s` contains a number. + ## Example: ``insertSep("1000000") == "1_000_000"`` + var L = (s.len-1) div digits + s.len + result = newString(L) + var j = 0 + dec(L) + for i in countdown(len(s)-1, 0): + if j == digits: + result[L] = sep + dec(L) + j = 0 + result[L] = s[i] + inc(j) + dec(L) + +proc escape*(s: string, prefix = "\"", suffix = "\""): string {.noSideEffect, + rtl, extern: "nsuEscape".} = + ## Escapes a string `s`. This does these operations (at the same time): + ## * replaces any ``\`` by ``\\`` + ## * replaces any ``'`` by ``\'`` + ## * replaces any ``"`` by ``\"`` + ## * replaces any other character in the set ``{'\0'..'\31', '\128'..'\255'}`` + ## by ``\xHH`` where ``HH`` is its hexadecimal value. + ## The procedure has been designed so that its output is usable for many + ## different common syntaxes. The resulting string is prefixed with + ## `prefix` and suffixed with `suffix`. Both may be empty strings. + result = newStringOfCap(s.len + s.len shr 2) + result.add(prefix) + for c in items(s): + case c + of '\0'..'\31', '\128'..'\255': + add(result, "\\x") + add(result, toHex(ord(c), 2)) + of '\\': add(result, "\\\\") + of '\'': add(result, "\\'") + of '\"': add(result, "\\\"") + else: add(result, c) + add(result, suffix) proc unescape*(s: string, prefix = "\"", suffix = "\""): string {.noSideEffect, rtl, extern: "nsuUnescape".} = @@ -920,323 +920,323 @@ proc unescape*(s: string, prefix = "\"", suffix = "\""): string {.noSideEffect, if s[i .. -1] != suffix: raise newException(EInvalidValue, "String does not end with a suffix of: " & suffix) - -proc validIdentifier*(s: string): bool {.noSideEffect, - rtl, extern: "nsuValidIdentifier".} = - ## returns true if `s` is a valid identifier. A valid identifier starts - ## with a character of the set `IdentStartChars` and is followed by any - ## number of characters of the set `IdentChars`. - if s[0] in IdentStartChars: - for i in 1..s.len-1: - if s[i] notin IdentChars: return false - return true - -proc editDistance*(a, b: string): int {.noSideEffect, - rtl, extern: "nsuEditDistance".} = - ## returns the edit distance between `a` and `b`. This uses the - ## `Levenshtein`:idx: distance algorithm with only a linear memory overhead. - ## This implementation is highly optimized! - var len1 = a.len - var len2 = b.len - if len1 > len2: - # make `b` the longer string - return editDistance(b, a) - - # strip common prefix: - var s = 0 - while a[s] == b[s] and a[s] != '\0': - inc(s) - dec(len1) - dec(len2) - # strip common suffix: - while len1 > 0 and len2 > 0 and a[s+len1-1] == b[s+len2-1]: - dec(len1) - dec(len2) - # trivial cases: - if len1 == 0: return len2 - if len2 == 0: return len1 - - # another special case: - if len1 == 1: - for j in s..len2-1: - if a[s] == b[j]: return len2 - 1 - return len2 - - inc(len1) - inc(len2) - var half = len1 shr 1 - # initalize first row: - #var row = cast[ptr array[0..high(int) div 8, int]](alloc(len2*sizeof(int))) - var row: seq[int] - newSeq(row, len2) - var e = s + len2 - 1 # end marker - for i in 1..len2 - half - 1: row[i] = i - row[0] = len1 - half - 1 - for i in 1 .. len1 - 1: - var char1 = a[i + s - 1] - var char2p: int - var D, x: int - var p: int - if i >= len1 - half: - # skip the upper triangle: - var offset = i - len1 + half - char2p = offset - p = offset - var c3 = row[p] + ord(char1 != b[s + char2p]) - inc(p) - inc(char2p) - x = row[p] + 1 - D = x - if x > c3: x = c3 - row[p] = x - inc(p) - else: - p = 1 - char2p = 0 - D = i - x = i - if i <= half + 1: - # skip the lower triangle: - e = len2 + i - half - 2 - # main: - while p <= e: - dec(D) - var c3 = D + ord(char1 != b[char2p + s]) - inc(char2p) - inc(x) - if x > c3: x = c3 - D = row[p] + 1 - if x > D: x = D - row[p] = x - inc(p) - # lower triangle sentinel: - if i <= half: - dec(D) - var c3 = D + ord(char1 != b[char2p + s]) - inc(x) - if x > c3: x = c3 - row[p] = x - result = row[e] - #dealloc(row) - - -# floating point formating: - -proc c_sprintf(buf, frmt: CString) {.header: "<stdio.h>", importc: "sprintf", - varargs, noSideEffect.} - -type - TFloatFormat* = enum ## the different modes of floating point formating - ffDefault, ## use the shorter floating point notation - ffDecimal, ## use decimal floating point notation - ffScientific ## use scientific notation (using ``e`` character) - -proc formatBiggestFloat*(f: BiggestFloat, format: TFloatFormat = ffDefault, + +proc validIdentifier*(s: string): bool {.noSideEffect, + rtl, extern: "nsuValidIdentifier".} = + ## returns true if `s` is a valid identifier. A valid identifier starts + ## with a character of the set `IdentStartChars` and is followed by any + ## number of characters of the set `IdentChars`. + if s[0] in IdentStartChars: + for i in 1..s.len-1: + if s[i] notin IdentChars: return false + return true + +proc editDistance*(a, b: string): int {.noSideEffect, + rtl, extern: "nsuEditDistance".} = + ## returns the edit distance between `a` and `b`. This uses the + ## `Levenshtein`:idx: distance algorithm with only a linear memory overhead. + ## This implementation is highly optimized! + var len1 = a.len + var len2 = b.len + if len1 > len2: + # make `b` the longer string + return editDistance(b, a) + + # strip common prefix: + var s = 0 + while a[s] == b[s] and a[s] != '\0': + inc(s) + dec(len1) + dec(len2) + # strip common suffix: + while len1 > 0 and len2 > 0 and a[s+len1-1] == b[s+len2-1]: + dec(len1) + dec(len2) + # trivial cases: + if len1 == 0: return len2 + if len2 == 0: return len1 + + # another special case: + if len1 == 1: + for j in s..len2-1: + if a[s] == b[j]: return len2 - 1 + return len2 + + inc(len1) + inc(len2) + var half = len1 shr 1 + # initalize first row: + #var row = cast[ptr array[0..high(int) div 8, int]](alloc(len2*sizeof(int))) + var row: seq[int] + newSeq(row, len2) + var e = s + len2 - 1 # end marker + for i in 1..len2 - half - 1: row[i] = i + row[0] = len1 - half - 1 + for i in 1 .. len1 - 1: + var char1 = a[i + s - 1] + var char2p: int + var D, x: int + var p: int + if i >= len1 - half: + # skip the upper triangle: + var offset = i - len1 + half + char2p = offset + p = offset + var c3 = row[p] + ord(char1 != b[s + char2p]) + inc(p) + inc(char2p) + x = row[p] + 1 + D = x + if x > c3: x = c3 + row[p] = x + inc(p) + else: + p = 1 + char2p = 0 + D = i + x = i + if i <= half + 1: + # skip the lower triangle: + e = len2 + i - half - 2 + # main: + while p <= e: + dec(D) + var c3 = D + ord(char1 != b[char2p + s]) + inc(char2p) + inc(x) + if x > c3: x = c3 + D = row[p] + 1 + if x > D: x = D + row[p] = x + inc(p) + # lower triangle sentinel: + if i <= half: + dec(D) + var c3 = D + ord(char1 != b[char2p + s]) + inc(x) + if x > c3: x = c3 + row[p] = x + result = row[e] + #dealloc(row) + + +# floating point formating: + +proc c_sprintf(buf, frmt: cstring) {.header: "<stdio.h>", importc: "sprintf", + varargs, noSideEffect.} + +type + TFloatFormat* = enum ## the different modes of floating point formating + ffDefault, ## use the shorter floating point notation + ffDecimal, ## use decimal floating point notation + ffScientific ## use scientific notation (using ``e`` character) + +proc formatBiggestFloat*(f: BiggestFloat, format: TFloatFormat = ffDefault, precision: range[0..32] = 16): string {. - noSideEffect, operator: 2, rtl, extern: "nsu$1".} = - ## converts a floating point value `f` to a string. - ## - ## If ``format == ffDecimal`` then precision is the number of digits to - ## be printed after the decimal point. - ## If ``format == ffScientific`` then precision is the maximum number - ## of significant digits to be printed. - ## `precision`'s default value is the maximum number of meaningful digits + noSideEffect, operator: 2, rtl, extern: "nsu$1".} = + ## converts a floating point value `f` to a string. + ## + ## If ``format == ffDecimal`` then precision is the number of digits to + ## be printed after the decimal point. + ## If ``format == ffScientific`` then precision is the maximum number + ## of significant digits to be printed. + ## `precision`'s default value is the maximum number of meaningful digits ## after the decimal point for Nimrod's ``biggestFloat`` type. ## - ## If ``precision == 0``, it tries to format it nicely. - const floatFormatToChar: array[TFloatFormat, char] = ['g', 'f', 'e'] - var - frmtstr {.noinit.}: array[0..5, char] - buf {.noinit.}: array[0..2500, char] - frmtstr[0] = '%' - if precision > 0: - frmtstr[1] = '#' - frmtstr[2] = '.' - frmtstr[3] = '*' - frmtstr[4] = floatFormatToChar[format] - frmtstr[5] = '\0' - c_sprintf(buf, frmtstr, precision, f) - else: - frmtstr[1] = floatFormatToChar[format] - frmtstr[2] = '\0' - c_sprintf(buf, frmtstr, f) - result = $buf - -proc formatFloat*(f: float, format: TFloatFormat = ffDefault, + ## If ``precision == 0``, it tries to format it nicely. + const floatFormatToChar: array[TFloatFormat, char] = ['g', 'f', 'e'] + var + frmtstr {.noinit.}: array[0..5, char] + buf {.noinit.}: array[0..2500, char] + frmtstr[0] = '%' + if precision > 0: + frmtstr[1] = '#' + frmtstr[2] = '.' + frmtstr[3] = '*' + frmtstr[4] = floatFormatToChar[format] + frmtstr[5] = '\0' + c_sprintf(buf, frmtstr, precision, f) + else: + frmtstr[1] = floatFormatToChar[format] + frmtstr[2] = '\0' + c_sprintf(buf, frmtstr, f) + result = $buf + +proc formatFloat*(f: float, format: TFloatFormat = ffDefault, precision: range[0..32] = 16): string {. - noSideEffect, operator: 2, rtl, extern: "nsu$1".} = - ## converts a floating point value `f` to a string. - ## - ## If ``format == ffDecimal`` then precision is the number of digits to - ## be printed after the decimal point. - ## If ``format == ffScientific`` then precision is the maximum number - ## of significant digits to be printed. - ## `precision`'s default value is the maximum number of meaningful digits - ## after the decimal point for Nimrod's ``float`` type. - result = formatBiggestFloat(f, format, precision) - -proc formatSize*(bytes: biggestInt, decimalSep = '.'): string = - ## Rounds and formats `bytes`. Examples: - ## - ## .. code-block:: nimrod - ## - ## formatSize(1'i64 shl 31 + 300'i64) == "2.204GB" - ## formatSize(4096) == "4KB" - ## - template frmt(a, b, c: expr): expr = - let bs = $b - insertSep($a) & decimalSep & bs.substr(0, 2) & c - let gigabytes = bytes shr 30 - let megabytes = bytes shr 20 - let kilobytes = bytes shr 10 - if gigabytes != 0: - result = frmt(gigabytes, megabytes, "GB") - elif megabytes != 0: - result = frmt(megabytes, kilobytes, "MB") - elif kilobytes != 0: - result = frmt(kilobytes, bytes, "KB") - else: - result = insertSep($bytes) & "B" - -proc findNormalized(x: string, inArray: openarray[string]): int = - var i = 0 - while i < high(inArray): - if cmpIgnoreStyle(x, inArray[i]) == 0: return i - inc(i, 2) # incrementing by 1 would probably lead to a - # security hole... - return -1 - -proc invalidFormatString() {.noinline.} = - raise newException(EInvalidValue, "invalid format string") - -proc addf*(s: var string, formatstr: string, a: varargs[string, `$`]) {. - noSideEffect, rtl, extern: "nsuAddf".} = - ## The same as ``add(s, formatstr % a)``, but more efficient. - const PatternChars = {'a'..'z', 'A'..'Z', '0'..'9', '\128'..'\255', '_'} - var i = 0 - var num = 0 - while i < len(formatstr): - if formatstr[i] == '$': - case formatstr[i+1] # again we use the fact that strings - # are zero-terminated here - of '#': - if num >% a.high: invalidFormatString() - add s, a[num] - inc i, 2 - inc num - of '$': - add s, '$' - inc(i, 2) - of '1'..'9', '-': - var j = 0 - inc(i) # skip $ - var negative = formatstr[i] == '-' - if negative: inc i - while formatstr[i] in Digits: - j = j * 10 + ord(formatstr[i]) - ord('0') - inc(i) - let idx = if not negative: j-1 else: a.len-j - if idx >% a.high: invalidFormatString() - add s, a[idx] - of '{': - var j = i+1 - while formatstr[j] notin {'\0', '}'}: inc(j) - var x = findNormalized(substr(formatstr, i+2, j-1), a) - if x >= 0 and x < high(a): add s, a[x+1] - else: invalidFormatString() - i = j+1 - of 'a'..'z', 'A'..'Z', '\128'..'\255', '_': - var j = i+1 - while formatstr[j] in PatternChars: inc(j) - var x = findNormalized(substr(formatstr, i+1, j-1), a) - if x >= 0 and x < high(a): add s, a[x+1] - else: invalidFormatString() - i = j - else: - invalidFormatString() - else: - add s, formatstr[i] - inc(i) - -proc `%` *(formatstr: string, a: openarray[string]): string {.noSideEffect, - rtl, extern: "nsuFormatOpenArray".} = - ## The `substitution`:idx: operator performs string substitutions in - ## `formatstr` and returns a modified `formatstr`. This is often called - ## `string interpolation`:idx:. - ## - ## This is best explained by an example: - ## - ## .. code-block:: nimrod - ## "$1 eats $2." % ["The cat", "fish"] - ## - ## Results in: - ## - ## .. code-block:: nimrod - ## "The cat eats fish." - ## - ## The substitution variables (the thing after the ``$``) are enumerated - ## from 1 to ``a.len``. - ## To produce a verbatim ``$``, use ``$$``. - ## The notation ``$#`` can be used to refer to the next substitution - ## variable: - ## - ## .. code-block:: nimrod - ## "$# eats $#." % ["The cat", "fish"] - ## - ## Substitution variables can also be words (that is - ## ``[A-Za-z_]+[A-Za-z0-9_]*``) in which case the arguments in `a` with even - ## indices are keys and with odd indices are the corresponding values. - ## An example: - ## - ## .. code-block:: nimrod - ## "$animal eats $food." % ["animal", "The cat", "food", "fish"] - ## - ## Results in: - ## - ## .. code-block:: nimrod - ## "The cat eats fish." - ## - ## The variables are compared with `cmpIgnoreStyle`. `EInvalidValue` is - ## raised if an ill-formed format string has been passed to the `%` operator. - result = newStringOfCap(formatstr.len + a.len shl 4) - addf(result, formatstr, a) - -proc `%` *(formatstr, a: string): string {.noSideEffect, - rtl, extern: "nsuFormatSingleElem".} = - ## This is the same as ``formatstr % [a]``. - result = newStringOfCap(formatstr.len + a.len) - addf(result, formatstr, [a]) - -proc format*(formatstr: string, a: varargs[string, `$`]): string {.noSideEffect, - rtl, extern: "nsuFormatVarargs".} = + noSideEffect, operator: 2, rtl, extern: "nsu$1".} = + ## converts a floating point value `f` to a string. + ## + ## If ``format == ffDecimal`` then precision is the number of digits to + ## be printed after the decimal point. + ## If ``format == ffScientific`` then precision is the maximum number + ## of significant digits to be printed. + ## `precision`'s default value is the maximum number of meaningful digits + ## after the decimal point for Nimrod's ``float`` type. + result = formatBiggestFloat(f, format, precision) + +proc formatSize*(bytes: BiggestInt, decimalSep = '.'): string = + ## Rounds and formats `bytes`. Examples: + ## + ## .. code-block:: nimrod + ## + ## formatSize(1'i64 shl 31 + 300'i64) == "2.204GB" + ## formatSize(4096) == "4KB" + ## + template frmt(a, b, c: expr): expr = + let bs = $b + insertSep($a) & decimalSep & bs.substr(0, 2) & c + let gigabytes = bytes shr 30 + let megabytes = bytes shr 20 + let kilobytes = bytes shr 10 + if gigabytes != 0: + result = frmt(gigabytes, megabytes, "GB") + elif megabytes != 0: + result = frmt(megabytes, kilobytes, "MB") + elif kilobytes != 0: + result = frmt(kilobytes, bytes, "KB") + else: + result = insertSep($bytes) & "B" + +proc findNormalized(x: string, inArray: openArray[string]): int = + var i = 0 + while i < high(inArray): + if cmpIgnoreStyle(x, inArray[i]) == 0: return i + inc(i, 2) # incrementing by 1 would probably lead to a + # security hole... + return -1 + +proc invalidFormatString() {.noinline.} = + raise newException(EInvalidValue, "invalid format string") + +proc addf*(s: var string, formatstr: string, a: varargs[string, `$`]) {. + noSideEffect, rtl, extern: "nsuAddf".} = + ## The same as ``add(s, formatstr % a)``, but more efficient. + const PatternChars = {'a'..'z', 'A'..'Z', '0'..'9', '\128'..'\255', '_'} + var i = 0 + var num = 0 + while i < len(formatstr): + if formatstr[i] == '$': + case formatstr[i+1] # again we use the fact that strings + # are zero-terminated here + of '#': + if num >% a.high: invalidFormatString() + add s, a[num] + inc i, 2 + inc num + of '$': + add s, '$' + inc(i, 2) + of '1'..'9', '-': + var j = 0 + inc(i) # skip $ + var negative = formatstr[i] == '-' + if negative: inc i + while formatstr[i] in Digits: + j = j * 10 + ord(formatstr[i]) - ord('0') + inc(i) + let idx = if not negative: j-1 else: a.len-j + if idx >% a.high: invalidFormatString() + add s, a[idx] + of '{': + var j = i+1 + while formatstr[j] notin {'\0', '}'}: inc(j) + var x = findNormalized(substr(formatstr, i+2, j-1), a) + if x >= 0 and x < high(a): add s, a[x+1] + else: invalidFormatString() + i = j+1 + of 'a'..'z', 'A'..'Z', '\128'..'\255', '_': + var j = i+1 + while formatstr[j] in PatternChars: inc(j) + var x = findNormalized(substr(formatstr, i+1, j-1), a) + if x >= 0 and x < high(a): add s, a[x+1] + else: invalidFormatString() + i = j + else: + invalidFormatString() + else: + add s, formatstr[i] + inc(i) + +proc `%` *(formatstr: string, a: openArray[string]): string {.noSideEffect, + rtl, extern: "nsuFormatOpenArray".} = + ## The `substitution`:idx: operator performs string substitutions in + ## `formatstr` and returns a modified `formatstr`. This is often called + ## `string interpolation`:idx:. + ## + ## This is best explained by an example: + ## + ## .. code-block:: nimrod + ## "$1 eats $2." % ["The cat", "fish"] + ## + ## Results in: + ## + ## .. code-block:: nimrod + ## "The cat eats fish." + ## + ## The substitution variables (the thing after the ``$``) are enumerated + ## from 1 to ``a.len``. + ## To produce a verbatim ``$``, use ``$$``. + ## The notation ``$#`` can be used to refer to the next substitution + ## variable: + ## + ## .. code-block:: nimrod + ## "$# eats $#." % ["The cat", "fish"] + ## + ## Substitution variables can also be words (that is + ## ``[A-Za-z_]+[A-Za-z0-9_]*``) in which case the arguments in `a` with even + ## indices are keys and with odd indices are the corresponding values. + ## An example: + ## + ## .. code-block:: nimrod + ## "$animal eats $food." % ["animal", "The cat", "food", "fish"] + ## + ## Results in: + ## + ## .. code-block:: nimrod + ## "The cat eats fish." + ## + ## The variables are compared with `cmpIgnoreStyle`. `EInvalidValue` is + ## raised if an ill-formed format string has been passed to the `%` operator. + result = newStringOfCap(formatstr.len + a.len shl 4) + addf(result, formatstr, a) + +proc `%` *(formatstr, a: string): string {.noSideEffect, + rtl, extern: "nsuFormatSingleElem".} = + ## This is the same as ``formatstr % [a]``. + result = newStringOfCap(formatstr.len + a.len) + addf(result, formatstr, [a]) + +proc format*(formatstr: string, a: varargs[string, `$`]): string {.noSideEffect, + rtl, extern: "nsuFormatVarargs".} = ## This is the same as ``formatstr % a`` except that it supports - ## auto stringification. - result = newStringOfCap(formatstr.len + a.len) - addf(result, formatstr, a) - -{.pop.} - -when isMainModule: - doAssert align("abc", 4) == " abc" - doAssert align("a", 0) == "a" - doAssert align("1232", 6) == " 1232" - doAssert align("1232", 6, '#') == "##1232" - echo wordWrap(""" this is a long text -- muchlongerthan10chars and here - it goes""", 10, false) - doAssert formatBiggestFloat(0.00000000001, ffDecimal, 11) == "0.00000000001" - doAssert formatBiggestFloat(0.00000000001, ffScientific, 1) == "1.0e-11" - - doAssert "$# $3 $# $#" % ["a", "b", "c"] == "a c b c" - echo formatSize(1'i64 shl 31 + 300'i64) # == "4,GB" - echo formatSize(1'i64 shl 31) - - doAssert "$animal eats $food." % ["animal", "The cat", "food", "fish"] == - "The cat eats fish." - - doAssert "-ld a-ldz -ld".replaceWord("-ld") == " a-ldz " - doAssert "-lda-ldz -ld abc".replaceWord("-ld") == "-lda-ldz abc" + ## auto stringification. + result = newStringOfCap(formatstr.len + a.len) + addf(result, formatstr, a) + +{.pop.} + +when isMainModule: + doAssert align("abc", 4) == " abc" + doAssert align("a", 0) == "a" + doAssert align("1232", 6) == " 1232" + doAssert align("1232", 6, '#') == "##1232" + echo wordWrap(""" this is a long text -- muchlongerthan10chars and here + it goes""", 10, false) + doAssert formatBiggestFloat(0.00000000001, ffDecimal, 11) == "0.00000000001" + doAssert formatBiggestFloat(0.00000000001, ffScientific, 1) == "1.0e-11" + + doAssert "$# $3 $# $#" % ["a", "b", "c"] == "a c b c" + echo formatSize(1'i64 shl 31 + 300'i64) # == "4,GB" + echo formatSize(1'i64 shl 31) + + doAssert "$animal eats $food." % ["animal", "The cat", "food", "fish"] == + "The cat eats fish." + + doAssert "-ld a-ldz -ld".replaceWord("-ld") == " a-ldz " + doAssert "-lda-ldz -ld abc".replaceWord("-ld") == "-lda-ldz abc" - type TMyEnum = enum enA, enB, enC, enuD, enE - doAssert parseEnum[TMyEnum]("enu_D") == enuD + type TMyEnum = enum enA, enB, enC, enuD, enE + doAssert parseEnum[TMyEnum]("enu_D") == enuD - doAssert parseEnum("invalid enum value", enC) == enC + doAssert parseEnum("invalid enum value", enC) == enC diff --git a/lib/pure/times.nim b/lib/pure/times.nim index a37091c52..6dfe80ca1 100644 --- a/lib/pure/times.nim +++ b/lib/pure/times.nim @@ -256,7 +256,7 @@ proc `+`*(a: TTimeInfo, interval: TTimeInterval): TTimeInfo = ## ## **Note:** This has been only briefly tested and it may not be ## very accurate. - let t = toSeconds(TimeInfoToTime(a)) + let t = toSeconds(timeInfoToTime(a)) let secs = toSeconds(a, interval) if a.tzname == "UTC": result = getGMTime(fromSeconds(t + secs)) @@ -268,7 +268,7 @@ proc `-`*(a: TTimeInfo, interval: TTimeInterval): TTimeInfo = ## ## **Note:** This has been only briefly tested, it is inaccurate especially ## when you subtract so much that you reach the Julian calendar. - let t = toSeconds(TimeInfoToTime(a)) + let t = toSeconds(timeInfoToTime(a)) let secs = toSeconds(a, interval) if a.tzname == "UTC": result = getGMTime(fromSeconds(t - secs)) @@ -319,11 +319,11 @@ when not defined(JS): importc: "gmtime", header: "<time.h>", tags: [].} proc timec(timer: PTime): TTime {. importc: "time", header: "<time.h>", tags: [].} - proc mktime(t: structTM): TTime {. + proc mktime(t: StructTM): TTime {. importc: "mktime", header: "<time.h>", tags: [].} - proc asctime(tblock: structTM): CString {. + proc asctime(tblock: StructTM): cstring {. importc: "asctime", header: "<time.h>", tags: [].} - proc ctime(time: PTime): CString {. + proc ctime(time: PTime): cstring {. importc: "ctime", header: "<time.h>", tags: [].} # strftime(s: CString, maxsize: int, fmt: CString, t: tm): int {. # importc: "strftime", header: "<time.h>".} @@ -335,7 +335,7 @@ when not defined(JS): clocksPerSec {.importc: "CLOCKS_PER_SEC", nodecl.}: int # our own procs on top of that: - proc tmToTimeInfo(tm: structTM, local: bool): TTimeInfo = + proc tmToTimeInfo(tm: StructTM, local: bool): TTimeInfo = const weekDays: array [0..6, TWeekDay] = [ dSun, dMon, dTue, dWed, dThu, dFri, dSat] @@ -358,7 +358,7 @@ when not defined(JS): timezone: if local: getTimezone() else: 0 ) - proc timeInfoToTM(t: TTimeInfo): structTM = + proc timeInfoToTM(t: TTimeInfo): StructTM = const weekDays: array [TWeekDay, int8] = [1'i8,2'i8,3'i8,4'i8,5'i8,6'i8,0'i8] result.second = t.second @@ -453,7 +453,7 @@ when not defined(JS): result = toFloat(a.tv_sec) + toFloat(a.tv_usec)*0.00_0001 elif defined(windows): var f: winlean.TFiletime - GetSystemTimeAsFileTime(f) + getSystemTimeAsFileTime(f) var i64 = rdFileTime(f) - epochDiff var secs = i64 div rateDiff var subsecs = i64 mod rateDiff diff --git a/lib/pure/unicode.nim b/lib/pure/unicode.nim index 1cf2816b4..b67341e89 100644 --- a/lib/pure/unicode.nim +++ b/lib/pure/unicode.nim @@ -109,7 +109,7 @@ proc runeAt*(s: string, i: int): TRune = proc toUTF8*(c: TRune): string {.rtl, extern: "nuc$1".} = ## converts a rune into its UTF8 representation - var i = irune(c) + var i = IRune(c) if i <=% 127: result = newString(1) result[0] = chr(i) @@ -1096,7 +1096,7 @@ const 0x01f1, 501, # 0x01f3, 499] # -proc binarySearch(c: irune, tab: openArray[iRune], len, stride: int): int = +proc binarySearch(c: IRune, tab: openArray[IRune], len, stride: int): int = var n = len var t = 0 while n > 1: @@ -1114,29 +1114,29 @@ proc binarySearch(c: irune, tab: openArray[iRune], len, stride: int): int = proc toLower*(c: TRune): TRune {.rtl, extern: "nuc$1", procvar.} = ## Converts `c` into lower case. This works for any Unicode character. ## If possible, prefer `toLower` over `toUpper`. - var c = irune(c) + var c = IRune(c) var p = binarySearch(c, tolowerRanges, len(toLowerRanges) div 3, 3) if p >= 0 and c >= tolowerRanges[p] and c <= tolowerRanges[p+1]: return TRune(c + tolowerRanges[p+2] - 500) p = binarySearch(c, toLowerSinglets, len(toLowerSinglets) div 2, 2) - if p >= 0 and c == toLowerSinglets[p]: - return TRune(c + toLowerSinglets[p+1] - 500) + if p >= 0 and c == tolowerSinglets[p]: + return TRune(c + tolowerSinglets[p+1] - 500) return TRune(c) proc toUpper*(c: TRune): TRune {.rtl, extern: "nuc$1", procvar.} = ## Converts `c` into upper case. This works for any Unicode character. ## If possible, prefer `toLower` over `toUpper`. - var c = irune(c) + var c = IRune(c) var p = binarySearch(c, toUpperRanges, len(toUpperRanges) div 3, 3) - if p >= 0 and c >= toUpperRanges[p] and c <= toUpperRanges[p+1]: - return TRune(c + toUpperRanges[p+2] - 500) + if p >= 0 and c >= toupperRanges[p] and c <= toupperRanges[p+1]: + return TRune(c + toupperRanges[p+2] - 500) p = binarySearch(c, toUpperSinglets, len(toUpperSinglets) div 2, 2) - if p >= 0 and c == toUpperSinglets[p]: - return TRune(c + toUpperSinglets[p+1] - 500) + if p >= 0 and c == toupperSinglets[p]: + return TRune(c + toupperSinglets[p+1] - 500) return TRune(c) proc toTitle*(c: TRune): TRune {.rtl, extern: "nuc$1", procvar.} = - var c = irune(c) + var c = IRune(c) var p = binarySearch(c, toTitleSinglets, len(toTitleSinglets) div 2, 2) if p >= 0 and c == toTitleSinglets[p]: return TRune(c + toTitleSinglets[p+1] - 500) @@ -1145,32 +1145,32 @@ proc toTitle*(c: TRune): TRune {.rtl, extern: "nuc$1", procvar.} = proc isLower*(c: TRune): bool {.rtl, extern: "nuc$1", procvar.} = ## returns true iff `c` is a lower case Unicode character ## If possible, prefer `isLower` over `isUpper`. - var c = irune(c) + var c = IRune(c) # Note: toUpperRanges is correct here! var p = binarySearch(c, toUpperRanges, len(toUpperRanges) div 3, 3) - if p >= 0 and c >= toUpperRanges[p] and c <= toUpperRanges[p+1]: + if p >= 0 and c >= toupperRanges[p] and c <= toupperRanges[p+1]: return true p = binarySearch(c, toUpperSinglets, len(toUpperSinglets) div 2, 2) - if p >= 0 and c == toUpperSinglets[p]: + if p >= 0 and c == toupperSinglets[p]: return true proc isUpper*(c: TRune): bool {.rtl, extern: "nuc$1", procvar.} = ## returns true iff `c` is a upper case Unicode character ## If possible, prefer `isLower` over `isUpper`. - var c = irune(c) + var c = IRune(c) # Note: toLowerRanges is correct here! var p = binarySearch(c, toLowerRanges, len(toLowerRanges) div 3, 3) - if p >= 0 and c >= toLowerRanges[p] and c <= toLowerRanges[p+1]: + if p >= 0 and c >= tolowerRanges[p] and c <= tolowerRanges[p+1]: return true p = binarySearch(c, toLowerSinglets, len(toLowerSinglets) div 2, 2) - if p >= 0 and c == toLowerSinglets[p]: + if p >= 0 and c == tolowerSinglets[p]: return true proc isAlpha*(c: TRune): bool {.rtl, extern: "nuc$1", procvar.} = ## returns true iff `c` is an *alpha* Unicode character (i.e. a letter) if isUpper(c) or isLower(c): return true - var c = irune(c) + var c = IRune(c) var p = binarySearch(c, alphaRanges, len(alphaRanges) div 2, 2) if p >= 0 and c >= alphaRanges[p] and c <= alphaRanges[p+1]: return true @@ -1183,7 +1183,7 @@ proc isTitle*(c: TRune): bool {.rtl, extern: "nuc$1", procvar.} = proc isWhiteSpace*(c: TRune): bool {.rtl, extern: "nuc$1", procvar.} = ## returns true iff `c` is a Unicode whitespace character - var c = irune(c) + var c = IRune(c) var p = binarySearch(c, spaceRanges, len(spaceRanges) div 2, 2) if p >= 0 and c >= spaceRanges[p] and c <= spaceRanges[p+1]: return true @@ -1210,7 +1210,7 @@ proc cmpRunesIgnoreCase*(a, b: string): int {.rtl, extern: "nuc$1", procvar.} = # slow path: fastRuneAt(a, i, ar) fastRuneAt(b, j, br) - result = irune(toLower(ar)) - irune(toLower(br)) + result = IRune(toLower(ar)) - IRune(toLower(br)) if result != 0: return result = a.len - b.len diff --git a/lib/system.nim b/lib/system.nim index da3fee35a..7df4be4df 100644 --- a/lib/system.nim +++ b/lib/system.nim @@ -339,13 +339,13 @@ type TResult* = enum Failure, Success -proc sizeof*[T](x: T): natural {.magic: "SizeOf", noSideEffect.} +proc sizeof*[T](x: T): Natural {.magic: "SizeOf", noSideEffect.} ## returns the size of ``x`` in bytes. Since this is a low-level proc, ## its usage is discouraged - using ``new`` for the most cases suffices ## that one never needs to know ``x``'s size. As a special semantic rule, ## ``x`` may also be a type identifier (``sizeof(int)`` is valid). -proc `<`*[T](x: ordinal[T]): T {.magic: "UnaryLt", noSideEffect.} +proc `<`*[T](x: Ordinal[T]): T {.magic: "UnaryLt", noSideEffect.} ## unary ``<`` that can be used for nice looking excluding ranges: ## ## .. code-block:: nimrod @@ -353,22 +353,22 @@ proc `<`*[T](x: ordinal[T]): T {.magic: "UnaryLt", noSideEffect.} ## ## Semantically this is the same as ``pred``. -proc succ*[T](x: ordinal[T], y = 1): T {.magic: "Succ", noSideEffect.} +proc succ*[T](x: Ordinal[T], y = 1): T {.magic: "Succ", noSideEffect.} ## returns the ``y``-th successor of the value ``x``. ``T`` has to be ## an ordinal type. If such a value does not exist, ``EOutOfRange`` is raised ## or a compile time error occurs. -proc pred*[T](x: ordinal[T], y = 1): T {.magic: "Pred", noSideEffect.} +proc pred*[T](x: Ordinal[T], y = 1): T {.magic: "Pred", noSideEffect.} ## returns the ``y``-th predecessor of the value ``x``. ``T`` has to be ## an ordinal type. If such a value does not exist, ``EOutOfRange`` is raised ## or a compile time error occurs. -proc inc*[T](x: var ordinal[T], y = 1) {.magic: "Inc", noSideEffect.} +proc inc*[T](x: var Ordinal[T], y = 1) {.magic: "Inc", noSideEffect.} ## increments the ordinal ``x`` by ``y``. If such a value does not ## exist, ``EOutOfRange`` is raised or a compile time error occurs. This is a ## short notation for: ``x = succ(x, y)``. -proc dec*[T](x: var ordinal[T], y = 1) {.magic: "Dec", noSideEffect.} +proc dec*[T](x: var Ordinal[T], y = 1) {.magic: "Dec", noSideEffect.} ## decrements the ordinal ``x`` by ``y``. If such a value does not ## exist, ``EOutOfRange`` is raised or a compile time error occurs. This is a ## short notation for: ``x = pred(x, y)``. @@ -591,43 +591,43 @@ type IntMax32 = bool|int|int8|int16|int32 proc `+%` *(x, y: IntMax32): IntMax32 {.magic: "AddU", noSideEffect.} -proc `+%` *(x, y: Int64): Int64 {.magic: "AddU", noSideEffect.} +proc `+%` *(x, y: int64): int64 {.magic: "AddU", noSideEffect.} ## treats `x` and `y` as unsigned and adds them. The result is truncated to ## fit into the result. This implements modulo arithmetic. No overflow ## errors are possible. proc `-%` *(x, y: IntMax32): IntMax32 {.magic: "SubU", noSideEffect.} -proc `-%` *(x, y: Int64): Int64 {.magic: "SubU", noSideEffect.} +proc `-%` *(x, y: int64): int64 {.magic: "SubU", noSideEffect.} ## treats `x` and `y` as unsigned and subtracts them. The result is ## truncated to fit into the result. This implements modulo arithmetic. ## No overflow errors are possible. proc `*%` *(x, y: IntMax32): IntMax32 {.magic: "MulU", noSideEffect.} -proc `*%` *(x, y: Int64): Int64 {.magic: "MulU", noSideEffect.} +proc `*%` *(x, y: int64): int64 {.magic: "MulU", noSideEffect.} ## treats `x` and `y` as unsigned and multiplies them. The result is ## truncated to fit into the result. This implements modulo arithmetic. ## No overflow errors are possible. proc `/%` *(x, y: IntMax32): IntMax32 {.magic: "DivU", noSideEffect.} -proc `/%` *(x, y: Int64): Int64 {.magic: "DivU", noSideEffect.} +proc `/%` *(x, y: int64): int64 {.magic: "DivU", noSideEffect.} ## treats `x` and `y` as unsigned and divides them. The result is ## truncated to fit into the result. This implements modulo arithmetic. ## No overflow errors are possible. proc `%%` *(x, y: IntMax32): IntMax32 {.magic: "ModU", noSideEffect.} -proc `%%` *(x, y: Int64): Int64 {.magic: "ModU", noSideEffect.} +proc `%%` *(x, y: int64): int64 {.magic: "ModU", noSideEffect.} ## treats `x` and `y` as unsigned and compute the modulo of `x` and `y`. ## The result is truncated to fit into the result. ## This implements modulo arithmetic. ## No overflow errors are possible. proc `<=%` *(x, y: IntMax32): bool {.magic: "LeU", noSideEffect.} -proc `<=%` *(x, y: Int64): bool {.magic: "LeU64", noSideEffect.} +proc `<=%` *(x, y: int64): bool {.magic: "LeU64", noSideEffect.} ## treats `x` and `y` as unsigned and compares them. ## Returns true iff ``unsigned(x) <= unsigned(y)``. proc `<%` *(x, y: IntMax32): bool {.magic: "LtU", noSideEffect.} -proc `<%` *(x, y: Int64): bool {.magic: "LtU64", noSideEffect.} +proc `<%` *(x, y: int64): bool {.magic: "LtU64", noSideEffect.} ## treats `x` and `y` as unsigned and compares them. ## Returns true iff ``unsigned(x) < unsigned(y)``. @@ -1064,7 +1064,7 @@ proc toFloat*(i: int): float {. ## fails, `EInvalidValue` is raised. However, on most platforms the ## conversion cannot fail. -proc toBiggestFloat*(i: biggestint): biggestfloat {. +proc toBiggestFloat*(i: BiggestInt): BiggestFloat {. magic: "ToBiggestFloat", noSideEffect, importc: "toBiggestFloat".} ## converts an biggestint `i` into a ``biggestfloat``. If the conversion ## fails, `EInvalidValue` is raised. However, on most platforms the @@ -1076,7 +1076,7 @@ proc toInt*(f: float): int {. ## rounds `f` if it does not contain an integer value. If the conversion ## fails (because `f` is infinite for example), `EInvalidValue` is raised. -proc toBiggestInt*(f: biggestfloat): biggestint {. +proc toBiggestInt*(f: BiggestFloat): BiggestInt {. magic: "ToBiggestInt", noSideEffect, importc: "toBiggestInt".} ## converts a biggestfloat `f` into a ``biggestint``. Conversion ## rounds `f` if it does not contain an integer value. If the conversion @@ -1118,19 +1118,19 @@ proc substr*(s: string, first, last: int): string {. ## or `limit`:idx: a string's length. when not defined(nimrodVM): - proc zeroMem*(p: Pointer, size: int) {.importc, noDecl.} + proc zeroMem*(p: pointer, size: int) {.importc, noDecl.} ## overwrites the contents of the memory at ``p`` with the value 0. ## Exactly ``size`` bytes will be overwritten. Like any procedure ## dealing with raw memory this is *unsafe*. - proc copyMem*(dest, source: Pointer, size: int) {. + proc copyMem*(dest, source: pointer, size: int) {. importc: "memcpy", header: "<string.h>".} ## copies the contents from the memory at ``source`` to the memory ## at ``dest``. Exactly ``size`` bytes will be copied. The memory ## regions may not overlap. Like any procedure dealing with raw ## memory this is *unsafe*. - proc moveMem*(dest, source: Pointer, size: int) {. + proc moveMem*(dest, source: pointer, size: int) {. importc: "memmove", header: "<string.h>".} ## copies the contents from the memory at ``source`` to the memory ## at ``dest``. Exactly ``size`` bytes will be copied. The memory @@ -1138,7 +1138,7 @@ when not defined(nimrodVM): ## and is thus somewhat more safe than ``copyMem``. Like any procedure ## dealing with raw memory this is still *unsafe*, though. - proc equalMem*(a, b: Pointer, size: int): bool {. + proc equalMem*(a, b: pointer, size: int): bool {. importc: "equalMem", noDecl, noSideEffect.} ## compares the memory blocks ``a`` and ``b``. ``size`` bytes will ## be compared. If the blocks are equal, true is returned, false @@ -1160,7 +1160,7 @@ when not defined(nimrodVM): ## containing zero, so it is somewhat safer than ``alloc``. ## The allocated memory belongs to its allocating thread! ## Use `allocShared0` to allocate from a shared heap. - proc realloc*(p: Pointer, newsize: int): pointer {.noconv, rtl, tags: [].} + proc realloc*(p: pointer, newsize: int): pointer {.noconv, rtl, tags: [].} ## grows or shrinks a given memory block. If p is **nil** then a new ## memory block is returned. In either way the block has at least ## ``newsize`` bytes. If ``newsize == 0`` and p is not **nil** @@ -1168,7 +1168,7 @@ when not defined(nimrodVM): ## be freed with ``dealloc``. ## The allocated memory belongs to its allocating thread! ## Use `reallocShared` to reallocate from a shared heap. - proc dealloc*(p: Pointer) {.noconv, rtl, tags: [].} + proc dealloc*(p: pointer) {.noconv, rtl, tags: [].} ## frees the memory allocated with ``alloc``, ``alloc0`` or ## ``realloc``. This procedure is dangerous! If one forgets to ## free the memory a leak occurs; if one tries to access freed @@ -1189,13 +1189,13 @@ when not defined(nimrodVM): ## ``reallocShared(block, 0)`` or ``deallocShared(block)``. ## The block is initialized with all bytes ## containing zero, so it is somewhat safer than ``allocShared``. - proc reallocShared*(p: Pointer, newsize: int): pointer {.noconv, rtl.} + proc reallocShared*(p: pointer, newsize: int): pointer {.noconv, rtl.} ## grows or shrinks a given memory block on the heap. If p is **nil** ## then a new memory block is returned. In either way the block has at least ## ``newsize`` bytes. If ``newsize == 0`` and p is not **nil** ## ``reallocShared`` calls ``deallocShared(p)``. In other cases the ## block has to be freed with ``deallocShared``. - proc deallocShared*(p: Pointer) {.noconv, rtl.} + proc deallocShared*(p: pointer) {.noconv, rtl.} ## frees the memory allocated with ``allocShared``, ``allocShared0`` or ## ``reallocShared``. This procedure is dangerous! If one forgets to ## free the memory a leak occurs; if one tries to access freed @@ -1240,7 +1240,7 @@ proc `$` *(x: char): string {.magic: "CharToStr", noSideEffect.} ## The stingify operator for a character argument. Returns `x` ## converted to a string. -proc `$` *(x: Cstring): string {.magic: "CStrToStr", noSideEffect.} +proc `$` *(x: cstring): string {.magic: "CStrToStr", noSideEffect.} ## The stingify operator for a CString argument. Returns `x` ## converted to a string. @@ -1428,7 +1428,7 @@ iterator items*(E: typedesc[enum]): E = for v in low(E)..high(E): yield v -iterator pairs*[T](a: openarray[T]): tuple[key: int, val: T] {.inline.} = +iterator pairs*[T](a: openArray[T]): tuple[key: int, val: T] {.inline.} = ## iterates over each item of `a`. Yields ``(index, a[index])`` pairs. var i = 0 while i < len(a): @@ -1963,14 +1963,14 @@ when not defined(JS): #and not defined(NimrodVM): ## `useStdoutAsStdmsg` compile-time switch. proc open*(f: var TFile, filename: string, - mode: TFileMode = fmRead, bufSize: int = -1): Bool {.tags: [].} + mode: TFileMode = fmRead, bufSize: int = -1): bool {.tags: [].} ## Opens a file named `filename` with given `mode`. ## ## Default mode is readonly. Returns true iff the file could be opened. ## This throws no exception if the file could not be opened. proc open*(f: var TFile, filehandle: TFileHandle, - mode: TFileMode = fmRead): Bool {.tags: [].} + mode: TFileMode = fmRead): bool {.tags: [].} ## Creates a ``TFile`` from a `filehandle` with given `mode`. ## ## Default mode is readonly. Returns true iff the file could be opened. @@ -1995,7 +1995,7 @@ when not defined(JS): #and not defined(NimrodVM): proc close*(f: TFile) {.importc: "fclose", header: "<stdio.h>", tags: [].} ## Closes the file. - proc endOfFile*(f: TFile): Bool {.tags: [].} + proc endOfFile*(f: TFile): bool {.tags: [].} ## Returns true iff `f` is at the end. proc readChar*(f: TFile): char {. @@ -2021,10 +2021,10 @@ when not defined(JS): #and not defined(NimrodVM): proc write*(f: TFile, r: float32) {.tags: [FWriteIO].} proc write*(f: TFile, i: int) {.tags: [FWriteIO].} - proc write*(f: TFile, i: biggestInt) {.tags: [FWriteIO].} - proc write*(f: TFile, r: biggestFloat) {.tags: [FWriteIO].} + proc write*(f: TFile, i: BiggestInt) {.tags: [FWriteIO].} + proc write*(f: TFile, r: BiggestFloat) {.tags: [FWriteIO].} proc write*(f: TFile, s: string) {.tags: [FWriteIO].} - proc write*(f: TFile, b: Bool) {.tags: [FWriteIO].} + proc write*(f: TFile, b: bool) {.tags: [FWriteIO].} proc write*(f: TFile, c: char) {.tags: [FWriteIO].} proc write*(f: TFile, c: cstring) {.tags: [FWriteIO].} proc write*(f: TFile, a: varargs[string, `$`]) {.tags: [FWriteIO].} @@ -2050,13 +2050,13 @@ when not defined(JS): #and not defined(NimrodVM): proc getFileSize*(f: TFile): int64 {.tags: [FReadIO].} ## retrieves the file size (in bytes) of `f`. - proc readBytes*(f: TFile, a: var openarray[int8], start, len: int): int {. + proc readBytes*(f: TFile, a: var openArray[int8], start, len: int): int {. tags: [FReadIO].} ## reads `len` bytes into the buffer `a` starting at ``a[start]``. Returns ## the actual number of bytes that have been read which may be less than ## `len` (if not as many bytes are remaining), but not greater. - proc readChars*(f: TFile, a: var openarray[char], start, len: int): int {. + proc readChars*(f: TFile, a: var openArray[char], start, len: int): int {. tags: [FReadIO].} ## reads `len` bytes into the buffer `a` starting at ``a[start]``. Returns ## the actual number of bytes that have been read which may be less than @@ -2067,13 +2067,13 @@ when not defined(JS): #and not defined(NimrodVM): ## the actual number of bytes that have been read which may be less than ## `len` (if not as many bytes are remaining), but not greater. - proc writeBytes*(f: TFile, a: openarray[int8], start, len: int): int {. + proc writeBytes*(f: TFile, a: openArray[int8], start, len: int): int {. tags: [FWriteIO].} ## writes the bytes of ``a[start..start+len-1]`` to the file `f`. Returns ## the number of actual written bytes, which may be less than `len` in case ## of an error. - proc writeChars*(f: tFile, a: openarray[char], start, len: int): int {. + proc writeChars*(f: TFile, a: openArray[char], start, len: int): int {. tags: [FWriteIO].} ## writes the bytes of ``a[start..start+len-1]`` to the file `f`. Returns ## the number of actual written bytes, which may be less than `len` in case @@ -2195,7 +2195,7 @@ when not defined(JS): #and not defined(NimrodVM): const GenericSeqSize = (2 * sizeof(int)) - proc getDiscriminant(aa: Pointer, n: ptr TNimNode): int = + proc getDiscriminant(aa: pointer, n: ptr TNimNode): int = sysAssert(n.kind == nkCase, "getDiscriminant: node != nkCase") var d: int var a = cast[TAddress](aa) @@ -2206,7 +2206,7 @@ when not defined(JS): #and not defined(NimrodVM): else: sysAssert(false, "getDiscriminant: invalid n.typ.size") return d - proc selectBranch(aa: Pointer, n: ptr TNimNode): ptr TNimNode = + proc selectBranch(aa: pointer, n: ptr TNimNode): ptr TNimNode = var discr = getDiscriminant(aa, n) if discr <% n.len: result = n.sons[discr] diff --git a/lib/system/alloc.nim b/lib/system/alloc.nim index e0f29a961..204d98a2c 100644 --- a/lib/system/alloc.nim +++ b/lib/system/alloc.nim @@ -109,7 +109,7 @@ type data: TTrunkBuckets type - TAlignType = biggestFloat + TAlignType = BiggestFloat TFreeCell {.final, pure.} = object next: ptr TFreeCell # next free cell in chunk (overlaid with refcount) zeroField: int # 0 means cell is not used (overlaid with typ field) @@ -260,7 +260,7 @@ proc intSetGet(t: TIntSet, key: int): PTrunk = result = nil proc intSetPut(a: var TMemRegion, t: var TIntSet, key: int): PTrunk = - result = IntSetGet(t, key) + result = intSetGet(t, key) if result == nil: result = cast[PTrunk](llAlloc(a, sizeof(result[]))) result.next = t.data[key and high(t.data)] @@ -268,7 +268,7 @@ proc intSetPut(a: var TMemRegion, t: var TIntSet, key: int): PTrunk = result.key = key proc contains(s: TIntSet, key: int): bool = - var t = IntSetGet(s, key shr TrunkShift) + var t = intSetGet(s, key shr TrunkShift) if t != nil: var u = key and TrunkMask result = (t.bits[u shr IntShift] and (1 shl (u and IntMask))) != 0 @@ -276,12 +276,12 @@ proc contains(s: TIntSet, key: int): bool = result = false proc incl(a: var TMemRegion, s: var TIntSet, key: int) = - var t = IntSetPut(a, s, key shr TrunkShift) + var t = intSetPut(a, s, key shr TrunkShift) var u = key and TrunkMask t.bits[u shr IntShift] = t.bits[u shr IntShift] or (1 shl (u and IntMask)) proc excl(s: var TIntSet, key: int) = - var t = IntSetGet(s, key shr TrunkShift) + var t = intSetGet(s, key shr TrunkShift) if t != nil: var u = key and TrunkMask t.bits[u shr IntShift] = t.bits[u shr IntShift] and not @@ -444,7 +444,7 @@ proc freeBigChunk(a: var TMemRegion, c: PBigChunk) = if isAccessible(a, ri) and chunkUnused(ri): sysAssert(not isSmallChunk(ri), "freeBigChunk 3") if not isSmallChunk(ri): - ListRemove(a.freeChunksList, cast[PBigChunk](ri)) + listRemove(a.freeChunksList, cast[PBigChunk](ri)) inc(c.size, ri.size) excl(a.chunkStarts, pageIndex(ri)) when coalescLeft: @@ -454,7 +454,7 @@ proc freeBigChunk(a: var TMemRegion, c: PBigChunk) = if isAccessible(a, le) and chunkUnused(le): sysAssert(not isSmallChunk(le), "freeBigChunk 5") if not isSmallChunk(le): - ListRemove(a.freeChunksList, cast[PBigChunk](le)) + listRemove(a.freeChunksList, cast[PBigChunk](le)) inc(le.size, c.size) excl(a.chunkStarts, pageIndex(c)) c = cast[PBigChunk](le) @@ -462,7 +462,7 @@ proc freeBigChunk(a: var TMemRegion, c: PBigChunk) = if c.size < ChunkOsReturn or weirdUnmap: incl(a, a.chunkStarts, pageIndex(c)) updatePrevSize(a, c, c.size) - ListAdd(a.freeChunksList, c) + listAdd(a.freeChunksList, c) c.used = false else: freeOsChunks(a, c, c.size) @@ -478,7 +478,7 @@ proc splitChunk(a: var TMemRegion, c: PBigChunk, size: int) = updatePrevSize(a, c, rest.size) c.size = size incl(a, a.chunkStarts, pageIndex(rest)) - ListAdd(a.freeChunksList, rest) + listAdd(a.freeChunksList, rest) proc getBigChunk(a: var TMemRegion, size: int): PBigChunk = # use first fit for now: @@ -489,10 +489,10 @@ proc getBigChunk(a: var TMemRegion, size: int): PBigChunk = while result != nil: sysAssert chunkUnused(result), "getBigChunk 3" if result.size == size: - ListRemove(a.freeChunksList, result) + listRemove(a.freeChunksList, result) break search elif result.size > size: - ListRemove(a.freeChunksList, result) + listRemove(a.freeChunksList, result) splitChunk(a, result, size) break search result = result.next @@ -531,7 +531,7 @@ proc allocInv(a: TMemRegion): bool = while it != nil: if it.zeroField != 0: echo "[SYSASSERT] it.zeroField != 0" - cprintf("%ld %p\n", it.zeroField, it) + c_printf("%ld %p\n", it.zeroField, it) return false it = it.next c = c.next @@ -557,7 +557,7 @@ proc rawAlloc(a: var TMemRegion, requestedSize: int): pointer = c.free = SmallChunkSize - smallChunkOverhead() - size c.next = nil c.prev = nil - ListAdd(a.freeSmallChunks[s], c) + listAdd(a.freeSmallChunks[s], c) result = addr(c.data) sysAssert((cast[TAddress](result) and (MemAlign-1)) == 0, "rawAlloc 4") else: @@ -581,7 +581,7 @@ proc rawAlloc(a: var TMemRegion, requestedSize: int): pointer = sysAssert(allocInv(a), "rawAlloc: before c.free < size") if c.free < size: sysAssert(allocInv(a), "rawAlloc: before listRemove test") - ListRemove(a.freeSmallChunks[s], c) + listRemove(a.freeSmallChunks[s], c) sysAssert(allocInv(a), "rawAlloc: end listRemove test") sysAssert(((cast[TAddress](result) and PageMask) - smallChunkOverhead()) %% size == 0, "rawAlloc 21") @@ -628,12 +628,12 @@ proc rawDealloc(a: var TMemRegion, p: pointer) = # check if it is not in the freeSmallChunks[s] list: if c.free < s: # add it to the freeSmallChunks[s] array: - ListAdd(a.freeSmallChunks[s div memAlign], c) + listAdd(a.freeSmallChunks[s div memAlign], c) inc(c.free, s) else: inc(c.free, s) if c.free == SmallChunkSize-smallChunkOverhead(): - ListRemove(a.freeSmallChunks[s div memAlign], c) + listRemove(a.freeSmallChunks[s div memAlign], c) c.size = SmallChunkSize freeBigChunk(a, cast[PBigChunk](c)) sysAssert(((cast[TAddress](p) and PageMask) - smallChunkOverhead()) %% @@ -802,13 +802,13 @@ template instantiateForRegion(allocator: expr) = when hasThreadSupport: var sharedHeap: TMemRegion var heapLock: TSysLock - initSysLock(HeapLock) + initSysLock(heapLock) proc allocShared(size: int): pointer = when hasThreadSupport: - acquireSys(HeapLock) + acquireSys(heapLock) result = alloc(sharedHeap, size) - releaseSys(HeapLock) + releaseSys(heapLock) else: result = alloc(size) @@ -818,17 +818,17 @@ template instantiateForRegion(allocator: expr) = proc deallocShared(p: pointer) = when hasThreadSupport: - acquireSys(HeapLock) + acquireSys(heapLock) dealloc(sharedHeap, p) - releaseSys(HeapLock) + releaseSys(heapLock) else: dealloc(p) proc reallocShared(p: pointer, newsize: int): pointer = when hasThreadSupport: - acquireSys(HeapLock) + acquireSys(heapLock) result = realloc(sharedHeap, p, newsize) - releaseSys(HeapLock) + releaseSys(heapLock) else: result = realloc(p, newsize) diff --git a/lib/system/ansi_c.nim b/lib/system/ansi_c.nim index 064597df6..2d33965e3 100644 --- a/lib/system/ansi_c.nim +++ b/lib/system/ansi_c.nim @@ -28,8 +28,8 @@ type final, incompleteStruct.} = object C_BinaryFile {.importc: "FILE", header: "<stdio.h>", final, incompleteStruct.} = object - C_TextFileStar = ptr CTextFile - C_BinaryFileStar = ptr CBinaryFile + C_TextFileStar = ptr C_TextFile + C_BinaryFileStar = ptr C_BinaryFile C_JmpBuf {.importc: "jmp_buf", header: "<setjmp.h>".} = object @@ -43,11 +43,11 @@ when not defined(SIGINT): when NoFakeVars: when defined(windows): const - SIGABRT = cint(22) - SIGFPE = cint(8) - SIGILL = cint(4) - SIGINT = cint(2) - SIGSEGV = cint(11) + SIGABRT = cint(22) + SIGFPE = cint(8) + SIGILL = cint(4) + SIGINT = cint(2) + SIGSEGV = cint(11) SIGTERM = cint(15) elif defined(macosx) or defined(linux): const diff --git a/lib/system/assign.nim b/lib/system/assign.nim index 525822620..6b7ffaf7b 100644 --- a/lib/system/assign.nim +++ b/lib/system/assign.nim @@ -7,10 +7,10 @@ # distribution, for details about the copyright. # -proc genericResetAux(dest: Pointer, n: ptr TNimNode) +proc genericResetAux(dest: pointer, n: ptr TNimNode) -proc genericAssignAux(dest, src: Pointer, mt: PNimType, shallow: bool) -proc genericAssignAux(dest, src: Pointer, n: ptr TNimNode, shallow: bool) = +proc genericAssignAux(dest, src: pointer, mt: PNimType, shallow: bool) +proc genericAssignAux(dest, src: pointer, n: ptr TNimNode, shallow: bool) = var d = cast[TAddress](dest) s = cast[TAddress](src) @@ -44,28 +44,28 @@ proc genericAssignAux(dest, src: Pointer, mt: PNimType, shallow: bool) = sysAssert(mt != nil, "genericAssignAux 2") case mt.Kind of tyString: - var x = cast[ppointer](dest) - var s2 = cast[ppointer](s)[] + var x = cast[PPointer](dest) + var s2 = cast[PPointer](s)[] if s2 == nil or shallow or ( cast[PGenericSeq](s2).reserved and seqShallowFlag) != 0: unsureAsgnRef(x, s2) else: unsureAsgnRef(x, copyString(cast[NimString](s2))) of tySequence: - var s2 = cast[ppointer](src)[] + var s2 = cast[PPointer](src)[] var seq = cast[PGenericSeq](s2) - var x = cast[ppointer](dest) + var x = cast[PPointer](dest) if s2 == nil or shallow or (seq.reserved and seqShallowFlag) != 0: # this can happen! nil sequences are allowed unsureAsgnRef(x, s2) return sysAssert(dest != nil, "genericAssignAux 3") unsureAsgnRef(x, newSeq(mt, seq.len)) - var dst = cast[taddress](cast[ppointer](dest)[]) + var dst = cast[TAddress](cast[PPointer](dest)[]) for i in 0..seq.len-1: genericAssignAux( cast[pointer](dst +% i*% mt.base.size +% GenericSeqSize), - cast[pointer](cast[taddress](s2) +% i *% mt.base.size +% + cast[pointer](cast[TAddress](s2) +% i *% mt.base.size +% GenericSeqSize), mt.Base, shallow) of tyObject: @@ -83,16 +83,16 @@ proc genericAssignAux(dest, src: Pointer, mt: PNimType, shallow: bool) = genericAssignAux(cast[pointer](d +% i*% mt.base.size), cast[pointer](s +% i*% mt.base.size), mt.base, shallow) of tyRef: - unsureAsgnRef(cast[ppointer](dest), cast[ppointer](s)[]) + unsureAsgnRef(cast[PPointer](dest), cast[PPointer](s)[]) else: copyMem(dest, src, mt.size) # copy raw bits -proc genericAssign(dest, src: Pointer, mt: PNimType) {.compilerProc.} = +proc genericAssign(dest, src: pointer, mt: PNimType) {.compilerProc.} = GC_disable() genericAssignAux(dest, src, mt, false) GC_enable() -proc genericShallowAssign(dest, src: Pointer, mt: PNimType) {.compilerProc.} = +proc genericShallowAssign(dest, src: pointer, mt: PNimType) {.compilerProc.} = GC_disable() genericAssignAux(dest, src, mt, true) GC_enable() @@ -126,7 +126,7 @@ when false: cprintf("%s %ld\n", k, t.size) debugNimType(t.base) -proc genericSeqAssign(dest, src: Pointer, mt: PNimType) {.compilerProc.} = +proc genericSeqAssign(dest, src: pointer, mt: PNimType) {.compilerProc.} = var src = src # ugly, but I like to stress the parser sometimes :-) genericAssign(dest, addr(src), mt) @@ -139,8 +139,8 @@ proc genericAssignOpenArray(dest, src: pointer, len: int, genericAssign(cast[pointer](d +% i*% mt.base.size), cast[pointer](s +% i*% mt.base.size), mt.base) -proc objectInit(dest: Pointer, typ: PNimType) {.compilerProc.} -proc objectInitAux(dest: Pointer, n: ptr TNimNode) = +proc objectInit(dest: pointer, typ: PNimType) {.compilerProc.} +proc objectInitAux(dest: pointer, n: ptr TNimNode) = var d = cast[TAddress](dest) case n.kind of nkNone: sysAssert(false, "objectInitAux") @@ -184,7 +184,7 @@ else: mixin destroy for i in countup(0, r.len - 1): destroy(r[i]) -proc genericReset(dest: Pointer, mt: PNimType) {.compilerProc.} +proc genericReset(dest: pointer, mt: PNimType) {.compilerProc.} proc genericResetAux(dest: Pointer, n: ptr TNimNode) = var d = cast[TAddress](dest) case n.kind @@ -202,7 +202,7 @@ proc genericReset(dest: Pointer, mt: PNimType) = sysAssert(mt != nil, "genericReset 2") case mt.Kind of tyString, tyRef, tySequence: - unsureAsgnRef(cast[ppointer](dest), nil) + unsureAsgnRef(cast[PPointer](dest), nil) of tyObject, tyTuple: # we don't need to reset m_type field for tyObject genericResetAux(dest, mt.node) diff --git a/lib/system/cellsets.nim b/lib/system/cellsets.nim index 85a24e856..9a22ed0c5 100644 --- a/lib/system/cellsets.nim +++ b/lib/system/cellsets.nim @@ -115,7 +115,7 @@ proc cellSetEnlarge(t: var TCellSet) = var oldMax = t.max t.max = ((t.max+1)*2)-1 var n = cast[PPageDescArray](alloc0((t.max + 1) * sizeof(PPageDesc))) - for i in 0 .. oldmax: + for i in 0 .. oldMax: if t.data[i] != nil: cellSetRawInsert(t, n, t.data[i]) dealloc(t.data) @@ -201,7 +201,7 @@ iterator elements(t: TCellSet): PCell {.inline.} = iterator elementsExcept(t, s: TCellSet): PCell {.inline.} = var r = t.head while r != nil: - let ss = CellSetGet(s, r.key) + let ss = cellSetGet(s, r.key) var i = 0 while i <= high(r.bits): var w = r.bits[i] diff --git a/lib/system/chcks.nim b/lib/system/chcks.nim index e78129483..eb1bf752e 100644 --- a/lib/system/chcks.nim +++ b/lib/system/chcks.nim @@ -9,7 +9,7 @@ # Implementation of some runtime checks. -proc raiseRangeError(val: biggestInt) {.compilerproc, noreturn, noinline.} = +proc raiseRangeError(val: BiggestInt) {.compilerproc, noreturn, noinline.} = when hostOs == "standalone": sysFatal(EOutOfRange, "value out of range") else: diff --git a/lib/system/excpt.nim b/lib/system/excpt.nim index e5f20f22a..5b00afc5b 100644 --- a/lib/system/excpt.nim +++ b/lib/system/excpt.nim @@ -17,7 +17,7 @@ var ## Unstable API. when not defined(windows) or not defined(guiapp): - proc writeToStdErr(msg: CString) = write(stdmsg, msg) + proc writeToStdErr(msg: cstring) = write(stdmsg, msg) else: proc MessageBoxA(hWnd: cint, lpText, lpCaption: cstring, uType: int): int32 {. @@ -240,7 +240,7 @@ proc raiseExceptionAux(e: ref E_Base) = showErrorMessage(buf) quitOrDebug() -proc raiseException(e: ref E_Base, ename: CString) {.compilerRtl.} = +proc raiseException(e: ref E_Base, ename: cstring) {.compilerRtl.} = e.name = ename when hasSomeStackTrace: e.trace = "" diff --git a/lib/system/gc.nim b/lib/system/gc.nim index 2daa3eafa..2a137d7fb 100644 --- a/lib/system/gc.nim +++ b/lib/system/gc.nim @@ -154,7 +154,7 @@ proc collectCT(gch: var TGcHeap) proc isOnStack*(p: pointer): bool {.noinline.} proc forAllChildren(cell: PCell, op: TWalkOp) proc doOperation(p: pointer, op: TWalkOp) -proc forAllChildrenAux(dest: Pointer, mt: PNimType, op: TWalkOp) +proc forAllChildrenAux(dest: pointer, mt: PNimType, op: TWalkOp) # we need the prototype here for debugging purposes when hasThreadSupport and hasSharedHeap: @@ -162,9 +162,9 @@ when hasThreadSupport and hasSharedHeap: template `++`(x: expr): stmt = discard atomicInc(x, rcIncrement) else: template `--`(x: expr): expr = - Dec(x, rcIncrement) + dec(x, rcIncrement) x <% rcIncrement - template `++`(x: expr): stmt = Inc(x, rcIncrement) + template `++`(x: expr): stmt = inc(x, rcIncrement) proc prepareDealloc(cell: PCell) = when useMarkForDebug: @@ -203,7 +203,7 @@ proc decRef(c: PCell) {.inline.} = gcAssert(c.refcount >=% rcIncrement, "decRef") if --c.refcount: rtlAddZCT(c) - elif canBeCycleRoot(c): + elif canbeCycleRoot(c): # unfortunately this is necessary here too, because a cycle might just # have been broken up and we could recycle it. rtlAddCycleRoot(c) @@ -214,7 +214,7 @@ proc incRef(c: PCell) {.inline.} = c.refcount = c.refCount +% rcIncrement # and not colorMask #writeCell("incRef", c) - if canBeCycleRoot(c): + if canbeCycleRoot(c): rtlAddCycleRoot(c) proc nimGCref(p: pointer) {.compilerProc, inline.} = incRef(usrToCell(p)) @@ -235,7 +235,7 @@ proc nimGCunrefNoCycle(p: pointer) {.compilerProc, inline.} = sysAssert(allocInv(gch.region), "end nimGCunrefNoCycle 2") sysAssert(allocInv(gch.region), "end nimGCunrefNoCycle 5") -proc asgnRef(dest: ppointer, src: pointer) {.compilerProc, inline.} = +proc asgnRef(dest: PPointer, src: pointer) {.compilerProc, inline.} = # the code generator calls this proc! gcAssert(not isOnStack(dest), "asgnRef") # BUGFIX: first incRef then decRef! @@ -243,7 +243,7 @@ proc asgnRef(dest: ppointer, src: pointer) {.compilerProc, inline.} = if dest[] != nil: decRef(usrToCell(dest[])) dest[] = src -proc asgnRefNoCycle(dest: ppointer, src: pointer) {.compilerProc, inline.} = +proc asgnRefNoCycle(dest: PPointer, src: pointer) {.compilerProc, inline.} = # the code generator calls this proc if it is known at compile time that no # cycle is possible. if src != nil: @@ -255,7 +255,7 @@ proc asgnRefNoCycle(dest: ppointer, src: pointer) {.compilerProc, inline.} = rtlAddZCT(c) dest[] = src -proc unsureAsgnRef(dest: ppointer, src: pointer) {.compilerProc.} = +proc unsureAsgnRef(dest: PPointer, src: pointer) {.compilerProc.} = # unsureAsgnRef updates the reference counters only if dest is not on the # stack. It is used by the code generator if it cannot decide wether a # reference is in the stack or not (this can happen for var parameters). @@ -318,7 +318,7 @@ proc forAllSlotsAux(dest: pointer, n: ptr TNimNode, op: TWalkOp) = # inlined for speed if n.sons[i].kind == nkSlot: if n.sons[i].typ.kind in {tyRef, tyString, tySequence}: - doOperation(cast[ppointer](d +% n.sons[i].offset)[], op) + doOperation(cast[PPointer](d +% n.sons[i].offset)[], op) else: forAllChildrenAux(cast[pointer](d +% n.sons[i].offset), n.sons[i].typ, op) @@ -335,7 +335,7 @@ proc forAllChildrenAux(dest: Pointer, mt: PNimType, op: TWalkOp) = if ntfNoRefs notin mt.flags: case mt.Kind of tyRef, tyString, tySequence: # leaf: - doOperation(cast[ppointer](d)[], op) + doOperation(cast[PPointer](d)[], op) of tyObject, tyTuple: forAllSlotsAux(dest, mt.node, op) of tyArray, tyArrayConstr, tyOpenArray: @@ -519,7 +519,7 @@ proc growObj(old: pointer, newsize: int, gch: var TGcHeap): pointer = d[j] = res break dec(j) - if canBeCycleRoot(ol): excl(gch.cycleRoots, ol) + if canbeCycleRoot(ol): excl(gch.cycleRoots, ol) when logGC: writeCell("growObj old cell", ol) writeCell("growObj new cell", res) @@ -869,7 +869,7 @@ else: sp = sp +% sizeof(pointer)*8 # last few entries: while sp <=% max: - gcMark(gch, cast[ppointer](sp)[]) + gcMark(gch, cast[PPointer](sp)[]) sp = sp +% sizeof(pointer) proc markStackAndRegisters(gch: var TGcHeap) {.noinline, cdecl.} = @@ -913,7 +913,7 @@ proc collectZCT(gch: var TGcHeap): bool = # In any case, it should be removed from the ZCT. But not # freed. **KEEP THIS IN MIND WHEN MAKING THIS INCREMENTAL!** when cycleGC: - if canBeCycleRoot(c): excl(gch.cycleRoots, c) + if canbeCycleRoot(c): excl(gch.cycleRoots, c) when logGC: writeCell("zct dealloc cell", c) gcTrace(c, csZctFreed) # We are about to free the object, call the finalizer BEFORE its diff --git a/lib/system/hti.nim b/lib/system/hti.nim index a2d132dbf..9d8ece7df 100644 --- a/lib/system/hti.nim +++ b/lib/system/hti.nim @@ -69,7 +69,7 @@ type kind: TNimNodeKind offset: int typ: ptr TNimType - name: Cstring + name: cstring len: int sons: ptr array [0..0x7fff, ptr TNimNode] diff --git a/lib/system/mmdisp.nim b/lib/system/mmdisp.nim index 942b6778e..a80fdad8f 100644 --- a/lib/system/mmdisp.nim +++ b/lib/system/mmdisp.nim @@ -33,7 +33,7 @@ const type PPointer = ptr pointer - TByteArray = array[0..1000_0000, byte] + TByteArray = array[0..1000_0000, Byte] PByte = ptr TByteArray PString = ptr string diff --git a/lib/system/repr.nim b/lib/system/repr.nim index f0d620952..aacf26653 100644 --- a/lib/system/repr.nim +++ b/lib/system/repr.nim @@ -96,7 +96,7 @@ proc reprSetAux(result: var string, p: pointer, typ: PNimType) = of 4: u = ze64(cast[ptr int32](p)[]) of 8: u = cast[ptr int64](p)[] else: - var a = cast[pbyteArray](p) + var a = cast[PByteArray](p) for i in 0 .. typ.size*8-1: if (ze(a[i div 8]) and (1 shl (i mod 8))) != 0: if elemCounter > 0: add result, ", " @@ -129,12 +129,12 @@ when not defined(useNimRtl): when hasThreadSupport and hasSharedHeap and defined(heapLock): AcquireSys(HeapLock) when defined(TCellSet): - Init(cl.marked) + init(cl.marked) cl.recdepth = -1 # default is to display everything! cl.indent = 0 proc deinitReprClosure(cl: var TReprClosure) = - when defined(TCellSet): Deinit(cl.marked) + when defined(TCellSet): deinit(cl.marked) when hasThreadSupport and hasSharedHeap and defined(heapLock): ReleaseSys(HeapLock) @@ -224,17 +224,17 @@ when not defined(useNimRtl): reprRecord(result, p, t, cl) of tyRef, tyPtr: sysAssert(p != nil, "reprAux") - if cast[ppointer](p)[] == nil: add result, "nil" - else: reprRef(result, cast[ppointer](p)[], typ, cl) + if cast[PPointer](p)[] == nil: add result, "nil" + else: reprRef(result, cast[PPointer](p)[], typ, cl) of tySequence: - reprSequence(result, cast[ppointer](p)[], typ, cl) + reprSequence(result, cast[PPointer](p)[], typ, cl) of tyInt: add result, $(cast[ptr int](p)[]) - of tyInt8: add result, $int(cast[ptr Int8](p)[]) - of tyInt16: add result, $int(cast[ptr Int16](p)[]) - of tyInt32: add result, $int(cast[ptr Int32](p)[]) - of tyInt64: add result, $(cast[ptr Int64](p)[]) - of tyUInt8: add result, $ze(cast[ptr Int8](p)[]) - of tyUInt16: add result, $ze(cast[ptr Int16](p)[]) + of tyInt8: add result, $int(cast[ptr int8](p)[]) + of tyInt16: add result, $int(cast[ptr int16](p)[]) + of tyInt32: add result, $int(cast[ptr int32](p)[]) + of tyInt64: add result, $(cast[ptr int64](p)[]) + of tyUInt8: add result, $ze(cast[ptr int8](p)[]) + of tyUInt16: add result, $ze(cast[ptr int16](p)[]) of tyFloat: add result, $(cast[ptr float](p)[]) of tyFloat32: add result, $(cast[ptr float32](p)[]) @@ -246,8 +246,8 @@ when not defined(useNimRtl): of tyCString: reprStrAux(result, $(cast[ptr cstring](p)[])) of tyRange: reprAux(result, p, typ.base, cl) of tyProc, tyPointer: - if cast[ppointer](p)[] == nil: add result, "nil" - else: add result, reprPointer(cast[ppointer](p)[]) + if cast[PPointer](p)[] == nil: add result, "nil" + else: add result, reprPointer(cast[PPointer](p)[]) else: add result, "(invalid data!)" inc(cl.recdepth) diff --git a/lib/system/sysio.nim b/lib/system/sysio.nim index 82b4b183a..9c0b0c589 100644 --- a/lib/system/sysio.nim +++ b/lib/system/sysio.nim @@ -24,16 +24,16 @@ proc fgetc(stream: TFile): cint {.importc: "fgetc", header: "<stdio.h>", tags: [FReadIO].} proc ungetc(c: cint, f: TFile) {.importc: "ungetc", header: "<stdio.h>", tags: [].} -proc putc(c: Char, stream: TFile) {.importc: "putc", header: "<stdio.h>", +proc putc(c: char, stream: TFile) {.importc: "putc", header: "<stdio.h>", tags: [FWriteIO].} -proc fprintf(f: TFile, frmt: CString) {.importc: "fprintf", +proc fprintf(f: TFile, frmt: cstring) {.importc: "fprintf", header: "<stdio.h>", varargs, tags: [FWriteIO].} proc strlen(c: cstring): int {. importc: "strlen", header: "<string.h>", tags: [].} # C routine that is used here: -proc fread(buf: Pointer, size, n: int, f: TFile): int {. +proc fread(buf: pointer, size, n: int, f: TFile): int {. importc: "fread", header: "<stdio.h>", tags: [FReadIO].} proc fseek(f: TFile, offset: clong, whence: int): int {. importc: "fseek", header: "<stdio.h>", tags: [].} @@ -48,7 +48,7 @@ proc write(f: TFile, c: cstring) = fputs(c, f) when NoFakeVars: when defined(windows): const - IOFBF = cint(0) + IOFBF = cint(0) IONBF = cint(4) elif defined(macosx) or defined(linux): const @@ -179,9 +179,9 @@ proc rawEchoNL() {.inline, compilerproc.} = write(stdout, "\n") when defined(windows) and not defined(useWinAnsi): include "system/widestrs" - proc wfopen(filename, mode: widecstring): pointer {. + proc wfopen(filename, mode: WideCString): pointer {. importc: "_wfopen", nodecl.} - proc wfreopen(filename, mode: widecstring, stream: TFile): TFile {. + proc wfreopen(filename, mode: WideCString, stream: TFile): TFile {. importc: "_wfreopen", nodecl.} proc fopen(filename, mode: cstring): pointer = diff --git a/lib/system/sysstr.nim b/lib/system/sysstr.nim index d62a987ff..bca14bb9d 100644 --- a/lib/system/sysstr.nim +++ b/lib/system/sysstr.nim @@ -63,14 +63,14 @@ proc copyStrLast(s: NimString, start, last: int): NimString {.compilerProc.} = proc copyStr(s: NimString, start: int): NimString {.compilerProc.} = result = copyStrLast(s, start, s.len-1) -proc toNimStr(str: CString, len: int): NimString {.compilerProc.} = +proc toNimStr(str: cstring, len: int): NimString {.compilerProc.} = result = rawNewString(len) result.len = len c_memcpy(result.data, str, (len+1) * sizeof(Char)) #result.data[len] = '\0' # readline relies on this! -proc cstrToNimstr(str: CString): NimString {.compilerRtl.} = - result = toNimstr(str, c_strlen(str)) +proc cstrToNimstr(str: cstring): NimString {.compilerRtl.} = + result = toNimStr(str, c_strlen(str)) proc copyString(src: NimString): NimString {.compilerRtl.} = if src != nil: @@ -98,8 +98,8 @@ proc hashString(s: string): int {.compilerproc.} = # the compiler needs exactly the same hash function! # this used to be used for efficient generation of string case statements var h = 0 - for i in 0..Len(s)-1: - h = h +% Ord(s[i]) + for i in 0..len(s)-1: + h = h +% ord(s[i]) h = h +% h shl 10 h = h xor (h shr 6) h = h +% h shl 3 @@ -150,10 +150,10 @@ proc addChar(s: NimString, c: char): NimString = # s = rawNewString(0); proc resizeString(dest: NimString, addlen: int): NimString {.compilerRtl.} = - if dest.len + addLen <= dest.space: + if dest.len + addlen <= dest.space: result = dest else: # slow path: - var sp = max(resize(dest.space), dest.len + addLen) + var sp = max(resize(dest.space), dest.len + addlen) result = cast[NimString](growObj(dest, sizeof(TGenericSeq) + sp + 1)) result.reserved = sp #result = rawNewString(sp) @@ -280,7 +280,7 @@ proc nimCharToStr(x: char): string {.compilerRtl.} = result = newString(1) result[0] = x -proc binaryStrSearch(x: openarray[string], y: string): int {.compilerproc.} = +proc binaryStrSearch(x: openArray[string], y: string): int {.compilerproc.} = var a = 0 b = len(x) diff --git a/lib/system/widestrs.nim b/lib/system/widestrs.nim index d856cc830..e2a5d87e9 100644 --- a/lib/system/widestrs.nim +++ b/lib/system/widestrs.nim @@ -1,153 +1,153 @@ -# -# -# Nimrod's Runtime Library -# (c) Copyright 2012 Andreas Rumpf -# -# See the file "copying.txt", included in this -# distribution, for details about the copyright. -# - -## Nimrod support for C/C++'s `wide strings`:idx:. This is part of the system -## module! Do not import it directly! +# +# +# Nimrod's Runtime Library +# (c) Copyright 2012 Andreas Rumpf +# +# See the file "copying.txt", included in this +# distribution, for details about the copyright. +# + +## Nimrod support for C/C++'s `wide strings`:idx:. This is part of the system +## module! Do not import it directly! when not defined(NimString): {.error: "You must not import this module explicitly".} - -type - TUtf16Char* = distinct int16 - WideCString* = ref array[0.. 1_000_000, TUtf16Char] - -proc len*(w: WideCString): int = - ## returns the length of a widestring. This traverses the whole string to - ## find the binary zero end marker! - while int16(w[result]) != 0'i16: inc result - -const - UNI_REPLACEMENT_CHAR = TUtf16Char(0xFFFD'i16) - UNI_MAX_BMP = 0x0000FFFF - UNI_MAX_UTF16 = 0x0010FFFF - UNI_MAX_UTF32 = 0x7FFFFFFF - UNI_MAX_LEGAL_UTF32 = 0x0010FFFF - - halfShift = 10 - halfBase = 0x0010000 - halfMask = 0x3FF - - UNI_SUR_HIGH_START = 0xD800 - UNI_SUR_HIGH_END = 0xDBFF - UNI_SUR_LOW_START = 0xDC00 - UNI_SUR_LOW_END = 0xDFFF - -template ones(n: expr): expr = ((1 shl n)-1) - -template fastRuneAt(s: cstring, i: int, result: expr, doInc = true) = - ## Returns the unicode character ``s[i]`` in `result`. If ``doInc == true`` - ## `i` is incremented by the number of bytes that have been processed. - bind ones - - if ord(s[i]) <=% 127: - result = ord(s[i]) - when doInc: inc(i) - elif ord(s[i]) shr 5 == 0b110: - #assert(ord(s[i+1]) shr 6 == 0b10) - result = (ord(s[i]) and (ones(5))) shl 6 or (ord(s[i+1]) and ones(6)) - when doInc: inc(i, 2) - elif ord(s[i]) shr 4 == 0b1110: - #assert(ord(s[i+1]) shr 6 == 0b10) - #assert(ord(s[i+2]) shr 6 == 0b10) - result = (ord(s[i]) and ones(4)) shl 12 or - (ord(s[i+1]) and ones(6)) shl 6 or - (ord(s[i+2]) and ones(6)) - when doInc: inc(i, 3) - elif ord(s[i]) shr 3 == 0b11110: - #assert(ord(s[i+1]) shr 6 == 0b10) - #assert(ord(s[i+2]) shr 6 == 0b10) - #assert(ord(s[i+3]) shr 6 == 0b10) - result = (ord(s[i]) and ones(3)) shl 18 or - (ord(s[i+1]) and ones(6)) shl 12 or - (ord(s[i+2]) and ones(6)) shl 6 or - (ord(s[i+3]) and ones(6)) - when doInc: inc(i, 4) - else: - result = 0xFFFD - when doInc: inc(i) - -iterator runes(s: cstring): int = - var - i = 0 - result: int - while s[i] != '\0': - fastRuneAt(s, i, result, true) - yield result - -proc newWideCString*(source: cstring, L: int): WideCString = + +type + TUtf16Char* = distinct int16 + WideCString* = ref array[0.. 1_000_000, TUtf16Char] + +proc len*(w: WideCString): int = + ## returns the length of a widestring. This traverses the whole string to + ## find the binary zero end marker! + while int16(w[result]) != 0'i16: inc result + +const + UNI_REPLACEMENT_CHAR = TUtf16Char(0xFFFD'i16) + UNI_MAX_BMP = 0x0000FFFF + UNI_MAX_UTF16 = 0x0010FFFF + UNI_MAX_UTF32 = 0x7FFFFFFF + UNI_MAX_LEGAL_UTF32 = 0x0010FFFF + + halfShift = 10 + halfBase = 0x0010000 + halfMask = 0x3FF + + UNI_SUR_HIGH_START = 0xD800 + UNI_SUR_HIGH_END = 0xDBFF + UNI_SUR_LOW_START = 0xDC00 + UNI_SUR_LOW_END = 0xDFFF + +template ones(n: expr): expr = ((1 shl n)-1) + +template fastRuneAt(s: cstring, i: int, result: expr, doInc = true) = + ## Returns the unicode character ``s[i]`` in `result`. If ``doInc == true`` + ## `i` is incremented by the number of bytes that have been processed. + bind ones + + if ord(s[i]) <=% 127: + result = ord(s[i]) + when doInc: inc(i) + elif ord(s[i]) shr 5 == 0b110: + #assert(ord(s[i+1]) shr 6 == 0b10) + result = (ord(s[i]) and (ones(5))) shl 6 or (ord(s[i+1]) and ones(6)) + when doInc: inc(i, 2) + elif ord(s[i]) shr 4 == 0b1110: + #assert(ord(s[i+1]) shr 6 == 0b10) + #assert(ord(s[i+2]) shr 6 == 0b10) + result = (ord(s[i]) and ones(4)) shl 12 or + (ord(s[i+1]) and ones(6)) shl 6 or + (ord(s[i+2]) and ones(6)) + when doInc: inc(i, 3) + elif ord(s[i]) shr 3 == 0b11110: + #assert(ord(s[i+1]) shr 6 == 0b10) + #assert(ord(s[i+2]) shr 6 == 0b10) + #assert(ord(s[i+3]) shr 6 == 0b10) + result = (ord(s[i]) and ones(3)) shl 18 or + (ord(s[i+1]) and ones(6)) shl 12 or + (ord(s[i+2]) and ones(6)) shl 6 or + (ord(s[i+3]) and ones(6)) + when doInc: inc(i, 4) + else: + result = 0xFFFD + when doInc: inc(i) + +iterator runes(s: cstring): int = + var + i = 0 + result: int + while s[i] != '\0': + fastRuneAt(s, i, result, true) + yield result + +proc newWideCString*(source: cstring, L: int): WideCString = unsafeNew(result, L * 4 + 2) - #result = cast[wideCString](alloc(L * 4 + 2)) - var d = 0 - for ch in runes(source): - if ch <=% UNI_MAX_BMP: - if ch >=% UNI_SUR_HIGH_START and ch <=% UNI_SUR_LOW_END: - result[d] = UNI_REPLACEMENT_CHAR - else: - result[d] = TUtf16Char(toU16(ch)) - elif ch >% UNI_MAX_UTF16: - result[d] = UNI_REPLACEMENT_CHAR - else: - let ch = ch -% halfBase - result[d] = TUtf16Char(toU16((ch shr halfShift) +% UNI_SUR_HIGH_START)) - inc d - result[d] = TUtf16Char(toU16((ch and halfMask) +% UNI_SUR_LOW_START)) - inc d - result[d] = TUtf16Char(0'i16) - -proc newWideCString*(s: cstring): WideCString = - if s.isNil: return nil - - when not defined(c_strlen): + #result = cast[wideCString](alloc(L * 4 + 2)) + var d = 0 + for ch in runes(source): + if ch <=% UNI_MAX_BMP: + if ch >=% UNI_SUR_HIGH_START and ch <=% UNI_SUR_LOW_END: + result[d] = UNI_REPLACEMENT_CHAR + else: + result[d] = TUtf16Char(toU16(ch)) + elif ch >% UNI_MAX_UTF16: + result[d] = UNI_REPLACEMENT_CHAR + else: + let ch = ch -% halfBase + result[d] = TUtf16Char(toU16((ch shr halfShift) +% UNI_SUR_HIGH_START)) + inc d + result[d] = TUtf16Char(toU16((ch and halfMask) +% UNI_SUR_LOW_START)) + inc d + result[d] = TUtf16Char(0'i16) + +proc newWideCString*(s: cstring): WideCString = + if s.isNil: return nil + + when not defined(c_strlen): proc c_strlen(a: cstring): int {. - header: "<string.h>", noSideEffect, importc: "strlen".} - - let L = cstrlen(s) - result = newWideCString(s, L) - -proc newWideCString*(s: string): WideCString = - result = newWideCString(s, s.len) - -proc `$`*(w: wideCString, estimate: int): string = - result = newStringOfCap(estimate + estimate shr 2) - - var i = 0 - while w[i].int16 != 0'i16: - var ch = w[i].int - inc i - if ch >=% UNI_SUR_HIGH_START and ch <=% UNI_SUR_HIGH_END: - # If the 16 bits following the high surrogate are in the source buffer... - let ch2 = w[i].int - # If it's a low surrogate, convert to UTF32: - if ch2 >=% UNI_SUR_LOW_START and ch2 <=% UNI_SUR_LOW_END: - ch = ((ch -% UNI_SUR_HIGH_START) shr halfShift) +% - (ch2 -% UNI_SUR_LOW_START) +% halfBase - inc i - - if ch <=% 127: - result.add chr(ch) - elif ch <=% 0x07FF: - result.add chr((ch shr 6) or 0b110_00000) - result.add chr((ch and ones(6)) or 0b10_000000) - elif ch <=% 0xFFFF: - result.add chr(ch shr 12 or 0b1110_0000) - result.add chr(ch shr 6 and ones(6) or 0b10_0000_00) - result.add chr(ch and ones(6) or 0b10_0000_00) - elif ch <=% 0x0010FFFF: - result.add chr(ch shr 18 or 0b1111_0000) - result.add chr(ch shr 12 and ones(6) or 0b10_0000_00) - result.add chr(ch shr 6 and ones(6) or 0b10_0000_00) - result.add chr(ch and ones(6) or 0b10_0000_00) - else: - # replacement char: - result.add chr(0xFFFD shr 12 or 0b1110_0000) - result.add chr(0xFFFD shr 6 and ones(6) or 0b10_0000_00) - result.add chr(0xFFFD and ones(6) or 0b10_0000_00) - -proc `$`*(s: WideCString): string = - result = s $ 80 + header: "<string.h>", noSideEffect, importc: "strlen".} + + let L = c_strlen(s) + result = newWideCString(s, L) + +proc newWideCString*(s: string): WideCString = + result = newWideCString(s, s.len) + +proc `$`*(w: WideCString, estimate: int): string = + result = newStringOfCap(estimate + estimate shr 2) + + var i = 0 + while w[i].int16 != 0'i16: + var ch = w[i].int + inc i + if ch >=% UNI_SUR_HIGH_START and ch <=% UNI_SUR_HIGH_END: + # If the 16 bits following the high surrogate are in the source buffer... + let ch2 = w[i].int + # If it's a low surrogate, convert to UTF32: + if ch2 >=% UNI_SUR_LOW_START and ch2 <=% UNI_SUR_LOW_END: + ch = ((ch -% UNI_SUR_HIGH_START) shr halfShift) +% + (ch2 -% UNI_SUR_LOW_START) +% halfBase + inc i + + if ch <=% 127: + result.add chr(ch) + elif ch <=% 0x07FF: + result.add chr((ch shr 6) or 0b110_00000) + result.add chr((ch and ones(6)) or 0b10_000000) + elif ch <=% 0xFFFF: + result.add chr(ch shr 12 or 0b1110_0000) + result.add chr(ch shr 6 and ones(6) or 0b10_0000_00) + result.add chr(ch and ones(6) or 0b10_0000_00) + elif ch <=% 0x0010FFFF: + result.add chr(ch shr 18 or 0b1111_0000) + result.add chr(ch shr 12 and ones(6) or 0b10_0000_00) + result.add chr(ch shr 6 and ones(6) or 0b10_0000_00) + result.add chr(ch and ones(6) or 0b10_0000_00) + else: + # replacement char: + result.add chr(0xFFFD shr 12 or 0b1110_0000) + result.add chr(0xFFFD shr 6 and ones(6) or 0b10_0000_00) + result.add chr(0xFFFD and ones(6) or 0b10_0000_00) + +proc `$`*(s: WideCString): string = + result = s $ 80 diff --git a/lib/windows/winlean.nim b/lib/windows/winlean.nim index 481f61fda..e288910d7 100644 --- a/lib/windows/winlean.nim +++ b/lib/windows/winlean.nim @@ -42,13 +42,13 @@ type wShowWindow*: int16 cbReserved2*: int16 lpReserved2*: pointer - hStdInput*: THANDLE - hStdOutput*: THANDLE - hStdError*: THANDLE + hStdInput*: THandle + hStdOutput*: THandle + hStdError*: THandle TPROCESS_INFORMATION* {.final, pure.} = object - hProcess*: THANDLE - hThread*: THANDLE + hProcess*: THandle + hThread*: THandle dwProcessId*: int32 dwThreadId*: int32 @@ -96,7 +96,7 @@ const CREATE_UNICODE_ENVIRONMENT* = 1024'i32 -proc closeHandle*(hObject: THANDLE): WINBOOL {.stdcall, dynlib: "kernel32", +proc closeHandle*(hObject: THandle): WINBOOL {.stdcall, dynlib: "kernel32", importc: "CloseHandle".} proc readFile*(hFile: THandle, Buffer: pointer, nNumberOfBytesToRead: int32, @@ -114,11 +114,11 @@ proc createPipe*(hReadPipe, hWritePipe: var THandle, stdcall, dynlib: "kernel32", importc: "CreatePipe".} when useWinUnicode: - proc createProcessW*(lpApplicationName, lpCommandLine: widecstring, + proc createProcessW*(lpApplicationName, lpCommandLine: WideCString, lpProcessAttributes: ptr TSECURITY_ATTRIBUTES, lpThreadAttributes: ptr TSECURITY_ATTRIBUTES, bInheritHandles: WINBOOL, dwCreationFlags: int32, - lpEnvironment, lpCurrentDirectory: widecstring, + lpEnvironment, lpCurrentDirectory: WideCString, lpStartupInfo: var TSTARTUPINFO, lpProcessInformation: var TPROCESS_INFORMATION): WINBOOL{. stdcall, dynlib: "kernel32", importc: "CreateProcessW".} @@ -134,25 +134,25 @@ else: stdcall, dynlib: "kernel32", importc: "CreateProcessA".} -proc suspendThread*(hThread: THANDLE): int32 {.stdcall, dynlib: "kernel32", +proc suspendThread*(hThread: THandle): int32 {.stdcall, dynlib: "kernel32", importc: "SuspendThread".} -proc resumeThread*(hThread: THANDLE): int32 {.stdcall, dynlib: "kernel32", +proc resumeThread*(hThread: THandle): int32 {.stdcall, dynlib: "kernel32", importc: "ResumeThread".} -proc waitForSingleObject*(hHandle: THANDLE, dwMilliseconds: int32): int32 {. +proc waitForSingleObject*(hHandle: THandle, dwMilliseconds: int32): int32 {. stdcall, dynlib: "kernel32", importc: "WaitForSingleObject".} -proc terminateProcess*(hProcess: THANDLE, uExitCode: int): WINBOOL {.stdcall, +proc terminateProcess*(hProcess: THandle, uExitCode: int): WINBOOL {.stdcall, dynlib: "kernel32", importc: "TerminateProcess".} -proc getExitCodeProcess*(hProcess: THANDLE, lpExitCode: var int32): WINBOOL {. +proc getExitCodeProcess*(hProcess: THandle, lpExitCode: var int32): WINBOOL {. stdcall, dynlib: "kernel32", importc: "GetExitCodeProcess".} -proc getStdHandle*(nStdHandle: int32): THANDLE {.stdcall, dynlib: "kernel32", +proc getStdHandle*(nStdHandle: int32): THandle {.stdcall, dynlib: "kernel32", importc: "GetStdHandle".} -proc setStdHandle*(nStdHandle: int32, hHandle: THANDLE): WINBOOL {.stdcall, +proc setStdHandle*(nStdHandle: int32, hHandle: THandle): WINBOOL {.stdcall, dynlib: "kernel32", importc: "SetStdHandle".} -proc flushFileBuffers*(hFile: THANDLE): WINBOOL {.stdcall, dynlib: "kernel32", +proc flushFileBuffers*(hFile: THandle): WINBOOL {.stdcall, dynlib: "kernel32", importc: "FlushFileBuffers".} proc getLastError*(): int32 {.importc: "GetLastError", @@ -176,18 +176,18 @@ proc localFree*(p: pointer) {. when useWinUnicode: proc getCurrentDirectoryW*(nBufferLength: int32, - lpBuffer: widecstring): int32 {. + lpBuffer: WideCString): int32 {. importc: "GetCurrentDirectoryW", dynlib: "kernel32", stdcall.} - proc setCurrentDirectoryW*(lpPathName: widecstring): int32 {. + proc setCurrentDirectoryW*(lpPathName: WideCString): int32 {. importc: "SetCurrentDirectoryW", dynlib: "kernel32", stdcall.} - proc createDirectoryW*(pathName: widecstring, security: Pointer=nil): int32 {. + proc createDirectoryW*(pathName: WideCString, security: pointer=nil): int32 {. importc: "CreateDirectoryW", dynlib: "kernel32", stdcall.} - proc removeDirectoryW*(lpPathName: widecstring): int32 {. + proc removeDirectoryW*(lpPathName: WideCString): int32 {. importc: "RemoveDirectoryW", dynlib: "kernel32", stdcall.} - proc setEnvironmentVariableW*(lpName, lpValue: widecstring): int32 {. + proc setEnvironmentVariableW*(lpName, lpValue: WideCString): int32 {. stdcall, dynlib: "kernel32", importc: "SetEnvironmentVariableW".} - proc getModuleFileNameW*(handle: THandle, buf: wideCString, + proc getModuleFileNameW*(handle: THandle, buf: WideCString, size: int32): int32 {.importc: "GetModuleFileNameW", dynlib: "kernel32", stdcall.} else: @@ -230,10 +230,10 @@ type cAlternateFileName*: array[0..13, TWinChar] when useWinUnicode: - proc findFirstFileW*(lpFileName: widecstring, - lpFindFileData: var TWIN32_FIND_DATA): THANDLE {. + proc findFirstFileW*(lpFileName: WideCString, + lpFindFileData: var TWIN32_FIND_DATA): THandle {. stdcall, dynlib: "kernel32", importc: "FindFirstFileW".} - proc findNextFileW*(hFindFile: THANDLE, + proc findNextFileW*(hFindFile: THandle, lpFindFileData: var TWIN32_FIND_DATA): int32 {. stdcall, dynlib: "kernel32", importc: "FindNextFileW".} else: @@ -244,32 +244,32 @@ else: lpFindFileData: var TWIN32_FIND_DATA): int32 {. stdcall, dynlib: "kernel32", importc: "FindNextFileA".} -proc findClose*(hFindFile: THANDLE) {.stdcall, dynlib: "kernel32", +proc findClose*(hFindFile: THandle) {.stdcall, dynlib: "kernel32", importc: "FindClose".} when useWinUnicode: - proc getFullPathNameW*(lpFileName: widecstring, nBufferLength: int32, - lpBuffer: widecstring, - lpFilePart: var widecstring): int32 {. + proc getFullPathNameW*(lpFileName: WideCString, nBufferLength: int32, + lpBuffer: WideCString, + lpFilePart: var WideCString): int32 {. stdcall, dynlib: "kernel32", importc: "GetFullPathNameW".} - proc getFileAttributesW*(lpFileName: widecstring): int32 {. + proc getFileAttributesW*(lpFileName: WideCString): int32 {. stdcall, dynlib: "kernel32", importc: "GetFileAttributesW".} - proc setFileAttributesW*(lpFileName: widecstring, + proc setFileAttributesW*(lpFileName: WideCString, dwFileAttributes: int32): WINBOOL {. stdcall, dynlib: "kernel32", importc: "SetFileAttributesW".} - proc copyFileW*(lpExistingFileName, lpNewFileName: wideCString, + proc copyFileW*(lpExistingFileName, lpNewFileName: WideCString, bFailIfExists: cint): cint {. importc: "CopyFileW", stdcall, dynlib: "kernel32".} - proc getEnvironmentStringsW*(): widecstring {. + proc getEnvironmentStringsW*(): WideCString {. stdcall, dynlib: "kernel32", importc: "GetEnvironmentStringsW".} - proc freeEnvironmentStringsW*(para1: widecstring): int32 {. + proc freeEnvironmentStringsW*(para1: WideCString): int32 {. stdcall, dynlib: "kernel32", importc: "FreeEnvironmentStringsW".} - proc getCommandLineW*(): wideCString {.importc: "GetCommandLineW", + proc getCommandLineW*(): WideCString {.importc: "GetCommandLineW", stdcall, dynlib: "kernel32".} else: @@ -299,7 +299,7 @@ else: proc rdFileTime*(f: TFILETIME): int64 = result = ze64(f.dwLowDateTime) or (ze64(f.dwHighDateTime) shl 32) -proc rdFileSize*(f: TWin32FindData): int64 = +proc rdFileSize*(f: TWIN32_FIND_DATA): int64 = result = ze64(f.nFileSizeLow) or (ze64(f.nFileSizeHigh) shl 32) proc getSystemTimeAsFileTime*(lpSystemTimeAsFileTime: var TFILETIME) {. @@ -310,7 +310,7 @@ proc sleep*(dwMilliseconds: int32){.stdcall, dynlib: "kernel32", when useWinUnicode: proc shellExecuteW*(HWND: THandle, lpOperation, lpFile, - lpParameters, lpDirectory: widecstring, + lpParameters, lpDirectory: WideCString, nShowCmd: int32): THandle{. stdcall, dynlib: "shell32.dll", importc: "ShellExecuteW".} @@ -445,10 +445,10 @@ proc getservbyname*(name, proto: cstring): ptr TServent {. proc getservbyport*(port: cint, proto: cstring): ptr TServent {. stdcall, importc: "getservbyport", dynlib: ws2dll.} -proc gethostbyaddr*(ip: ptr TInAddr, len: cuint, theType: cint): ptr THostEnt {. +proc gethostbyaddr*(ip: ptr TInAddr, len: cuint, theType: cint): ptr Thostent {. stdcall, importc: "gethostbyaddr", dynlib: ws2dll.} -proc gethostbyname*(name: cstring): ptr THostEnt {. +proc gethostbyname*(name: cstring): ptr Thostent {. stdcall, importc: "gethostbyname", dynlib: ws2dll.} proc socket*(af, typ, protocol: cint): TSocketHandle {. @@ -457,20 +457,20 @@ proc socket*(af, typ, protocol: cint): TSocketHandle {. proc closesocket*(s: TSocketHandle): cint {. stdcall, importc: "closesocket", dynlib: ws2dll.} -proc accept*(s: TSocketHandle, a: ptr TSockAddr, addrlen: ptr TSockLen): TSocketHandle {. +proc accept*(s: TSocketHandle, a: ptr TSockAddr, addrlen: ptr Tsocklen): TSocketHandle {. stdcall, importc: "accept", dynlib: ws2dll.} -proc bindSocket*(s: TSocketHandle, name: ptr TSockAddr, namelen: TSockLen): cint {. +proc bindSocket*(s: TSocketHandle, name: ptr TSockAddr, namelen: Tsocklen): cint {. stdcall, importc: "bind", dynlib: ws2dll.} -proc connect*(s: TSocketHandle, name: ptr TSockAddr, namelen: TSockLen): cint {. +proc connect*(s: TSocketHandle, name: ptr TSockAddr, namelen: Tsocklen): cint {. stdcall, importc: "connect", dynlib: ws2dll.} proc getsockname*(s: TSocketHandle, name: ptr TSockAddr, - namelen: ptr TSockLen): cint {. + namelen: ptr Tsocklen): cint {. stdcall, importc: "getsockname", dynlib: ws2dll.} proc getsockopt*(s: TSocketHandle, level, optname: cint, optval: pointer, - optlen: ptr TSockLen): cint {. + optlen: ptr Tsocklen): cint {. stdcall, importc: "getsockopt", dynlib: ws2dll.} proc setsockopt*(s: TSocketHandle, level, optname: cint, optval: pointer, - optlen: TSockLen): cint {. + optlen: Tsocklen): cint {. stdcall, importc: "setsockopt", dynlib: ws2dll.} proc listen*(s: TSocketHandle, backlog: cint): cint {. @@ -492,7 +492,7 @@ proc sendto*(s: TSocketHandle, buf: pointer, len, flags: cint, proc shutdown*(s: TSocketHandle, how: cint): cint {. stdcall, importc: "shutdown", dynlib: ws2dll.} -proc getnameinfo*(a1: ptr Tsockaddr, a2: Tsocklen, +proc getnameinfo*(a1: ptr TSockAddr, a2: Tsocklen, a3: cstring, a4: Tsocklen, a5: cstring, a6: Tsocklen, a7: cint): cint {. stdcall, importc: "getnameinfo", dynlib: ws2dll.} @@ -500,18 +500,18 @@ proc getnameinfo*(a1: ptr Tsockaddr, a2: Tsocklen, proc inet_addr*(cp: cstring): int32 {. stdcall, importc: "inet_addr", dynlib: ws2dll.} -proc WSAFDIsSet(s: TSocketHandle, FDSet: var TFDSet): bool {. +proc WSAFDIsSet(s: TSocketHandle, FDSet: var TFdSet): bool {. stdcall, importc: "__WSAFDIsSet", dynlib: ws2dll.} -proc FD_ISSET*(Socket: TSocketHandle, FDSet: var TFDSet): cint = +proc FD_ISSET*(Socket: TSocketHandle, FDSet: var TFdSet): cint = result = if WSAFDIsSet(Socket, FDSet): 1'i32 else: 0'i32 -proc FD_SET*(Socket: TSocketHandle, FDSet: var TFDSet) = +proc FD_SET*(Socket: TSocketHandle, FDSet: var TFdSet) = if FDSet.fd_count < FD_SETSIZE: FDSet.fd_array[int(FDSet.fd_count)] = Socket inc(FDSet.fd_count) -proc FD_ZERO*(FDSet: var TFDSet) = +proc FD_ZERO*(FDSet: var TFdSet) = FDSet.fd_count = 0 proc WSAStartup*(wVersionRequired: int16, WSData: ptr TWSAData): cint {. @@ -531,7 +531,7 @@ const MAXIMUM_WAIT_OBJECTS* = 0x00000040 type - TWOHandleArray* = array[0..MAXIMUM_WAIT_OBJECTS - 1, THANDLE] + TWOHandleArray* = array[0..MAXIMUM_WAIT_OBJECTS - 1, THandle] PWOHandleArray* = ptr TWOHandleArray proc waitForMultipleObjects*(nCount: DWORD, lpHandles: PWOHandleArray, @@ -566,12 +566,12 @@ const ERROR_ACCESS_DENIED* = 5 when useWinUnicode: - proc createFileW*(lpFileName: widecstring, dwDesiredAccess, dwShareMode: DWORD, + proc createFileW*(lpFileName: WideCString, dwDesiredAccess, dwShareMode: DWORD, lpSecurityAttributes: pointer, dwCreationDisposition, dwFlagsAndAttributes: DWORD, - hTemplateFile: THANDLE): THANDLE {. + hTemplateFile: THandle): THandle {. stdcall, dynlib: "kernel32", importc: "CreateFileW".} - proc deleteFileW*(pathName: widecstring): int32 {. + proc deleteFileW*(pathName: WideCString): int32 {. importc: "DeleteFileW", dynlib: "kernel32", stdcall.} else: proc createFileA*(lpFileName: cstring, dwDesiredAccess, dwShareMode: DWORD, @@ -582,28 +582,28 @@ else: proc deleteFileA*(pathName: cstring): int32 {. importc: "DeleteFileA", dynlib: "kernel32", stdcall.} -proc setEndOfFile*(hFile: THANDLE): WINBOOL {.stdcall, dynlib: "kernel32", +proc setEndOfFile*(hFile: THandle): WINBOOL {.stdcall, dynlib: "kernel32", importc: "SetEndOfFile".} -proc setFilePointer*(hFile: THANDLE, lDistanceToMove: LONG, +proc setFilePointer*(hFile: THandle, lDistanceToMove: LONG, lpDistanceToMoveHigh: ptr LONG, dwMoveMethod: DWORD): DWORD {. stdcall, dynlib: "kernel32", importc: "SetFilePointer".} -proc getFileSize*(hFile: THANDLE, lpFileSizeHigh: ptr DWORD): DWORD{.stdcall, +proc getFileSize*(hFile: THandle, lpFileSizeHigh: ptr DWORD): DWORD{.stdcall, dynlib: "kernel32", importc: "GetFileSize".} -proc mapViewOfFileEx*(hFileMappingObject: THANDLE, dwDesiredAccess: DWORD, +proc mapViewOfFileEx*(hFileMappingObject: THandle, dwDesiredAccess: DWORD, dwFileOffsetHigh, dwFileOffsetLow: DWORD, dwNumberOfBytesToMap: DWORD, lpBaseAddress: pointer): pointer{. stdcall, dynlib: "kernel32", importc: "MapViewOfFileEx".} -proc createFileMappingW*(hFile: THANDLE, +proc createFileMappingW*(hFile: THandle, lpFileMappingAttributes: pointer, flProtect, dwMaximumSizeHigh: DWORD, dwMaximumSizeLow: DWORD, - lpName: pointer): THANDLE {. + lpName: pointer): THandle {. stdcall, dynlib: "kernel32", importc: "CreateFileMappingW".} when not useWinUnicode: |