case consistency part 6

This commit is contained in:
Araq 2013-12-28 01:17:02 +01:00
commit bf205fa85d
7 changed files with 169 additions and 169 deletions

View file

@ -147,15 +147,15 @@ proc del*(father: PNimrodNode, idx = 0, n = 1) {.magic: "NDel".}
proc kind*(n: PNimrodNode): TNimrodNodeKind {.magic: "NKind".} proc kind*(n: PNimrodNode): TNimrodNodeKind {.magic: "NKind".}
## returns the `kind` of the node `n`. ## returns the `kind` of the node `n`.
proc intVal*(n: PNimrodNode): biggestInt {.magic: "NIntVal".} proc intVal*(n: PNimrodNode): BiggestInt {.magic: "NIntVal".}
proc floatVal*(n: PNimrodNode): biggestFloat {.magic: "NFloatVal".} proc floatVal*(n: PNimrodNode): BiggestFloat {.magic: "NFloatVal".}
proc symbol*(n: PNimrodNode): PNimrodSymbol {.magic: "NSymbol".} proc symbol*(n: PNimrodNode): PNimrodSymbol {.magic: "NSymbol".}
proc ident*(n: PNimrodNode): TNimrodIdent {.magic: "NIdent".} proc ident*(n: PNimrodNode): TNimrodIdent {.magic: "NIdent".}
proc typ*(n: PNimrodNode): typedesc {.magic: "NGetType".} proc typ*(n: PNimrodNode): typedesc {.magic: "NGetType".}
proc strVal*(n: PNimrodNode): string {.magic: "NStrVal".} proc strVal*(n: PNimrodNode): string {.magic: "NStrVal".}
proc `intVal=`*(n: PNimrodNode, val: biggestInt) {.magic: "NSetIntVal".} proc `intVal=`*(n: PNimrodNode, val: BiggestInt) {.magic: "NSetIntVal".}
proc `floatVal=`*(n: PNimrodNode, val: biggestFloat) {.magic: "NSetFloatVal".} proc `floatVal=`*(n: PNimrodNode, val: BiggestFloat) {.magic: "NSetFloatVal".}
proc `symbol=`*(n: PNimrodNode, val: PNimrodSymbol) {.magic: "NSetSymbol".} proc `symbol=`*(n: PNimrodNode, val: PNimrodSymbol) {.magic: "NSetSymbol".}
proc `ident=`*(n: PNimrodNode, val: TNimrodIdent) {.magic: "NSetIdent".} proc `ident=`*(n: PNimrodNode, val: TNimrodIdent) {.magic: "NSetIdent".}
#proc `typ=`*(n: PNimrodNode, typ: typedesc) {.magic: "NSetType".} #proc `typ=`*(n: PNimrodNode, typ: typedesc) {.magic: "NSetType".}
@ -187,12 +187,12 @@ proc newStrLitNode*(s: string): PNimrodNode {.compileTime.} =
result = newNimNode(nnkStrLit) result = newNimNode(nnkStrLit)
result.strVal = s result.strVal = s
proc newIntLitNode*(i: biggestInt): PNimrodNode {.compileTime.} = proc newIntLitNode*(i: BiggestInt): PNimrodNode {.compileTime.} =
## creates a int literal node from `i` ## creates a int literal node from `i`
result = newNimNode(nnkIntLit) result = newNimNode(nnkIntLit)
result.intVal = i result.intVal = i
proc newFloatLitNode*(f: biggestFloat): PNimrodNode {.compileTime.} = proc newFloatLitNode*(f: BiggestFloat): PNimrodNode {.compileTime.} =
## creates a float literal node from `f` ## creates a float literal node from `f`
result = newNimNode(nnkFloatLit) result = newNimNode(nnkFloatLit)
result.floatVal = f result.floatVal = f
@ -351,12 +351,12 @@ proc newLit*(c: char): PNimrodNode {.compileTime.} =
result = newNimNode(nnkCharLit) result = newNimNode(nnkCharLit)
result.intVal = ord(c) result.intVal = ord(c)
proc newLit*(i: biggestInt): PNimrodNode {.compileTime.} = proc newLit*(i: BiggestInt): PNimrodNode {.compileTime.} =
## produces a new integer literal node. ## produces a new integer literal node.
result = newNimNode(nnkIntLit) result = newNimNode(nnkIntLit)
result.intVal = i result.intVal = i
proc newLit*(f: biggestFloat): PNimrodNode {.compileTime.} = proc newLit*(f: BiggestFloat): PNimrodNode {.compileTime.} =
## produces a new float literal node. ## produces a new float literal node.
result = newNimNode(nnkFloatLit) result = newNimNode(nnkFloatLit)
result.floatVal = f result.floatVal = f
@ -535,7 +535,7 @@ from strutils import cmpIgnoreStyle, format
proc expectKind*(n: PNimrodNode; k: set[TNimrodNodeKind]) {.compileTime.} = proc expectKind*(n: PNimrodNode; k: set[TNimrodNodeKind]) {.compileTime.} =
assert n.kind in k, "Expected one of $1, got $2".format(k, n.kind) assert n.kind in k, "Expected one of $1, got $2".format(k, n.kind)
proc newProc*(name = newEmptyNode(); params: openarray[PNimrodNode] = [newEmptyNode()]; proc newProc*(name = newEmptyNode(); params: openArray[PNimrodNode] = [newEmptyNode()];
body: PNimrodNode = newStmtList(), procType = nnkProcDef): PNimrodNode {.compileTime.} = body: PNimrodNode = newStmtList(), procType = nnkProcDef): PNimrodNode {.compileTime.} =
## shortcut for creating a new proc ## shortcut for creating a new proc
## ##
@ -573,7 +573,7 @@ proc copyChildrenTo*(src, dest: PNimrodNode) {.compileTime.}=
dest.add src[i].copyNimTree dest.add src[i].copyNimTree
template expectRoutine(node: PNimrodNode): stmt = template expectRoutine(node: PNimrodNode): stmt =
expectKind(node, routineNodes) expectKind(node, RoutineNodes)
proc name*(someProc: PNimrodNode): PNimrodNode {.compileTime.} = proc name*(someProc: PNimrodNode): PNimrodNode {.compileTime.} =
someProc.expectRoutine someProc.expectRoutine
@ -610,7 +610,7 @@ proc body*(someProc: PNimrodNode): PNimrodNode {.compileTime.} =
of routineNodes: of routineNodes:
return someProc[6] return someProc[6]
of nnkBlockStmt, nnkWhileStmt: of nnkBlockStmt, nnkWhileStmt:
return someproc[1] return someProc[1]
of nnkForStmt: of nnkForStmt:
return someProc.last return someProc.last
else: else:
@ -634,7 +634,7 @@ proc `$`*(node: PNimrodNode): string {.compileTime.} =
of nnkIdent: of nnkIdent:
result = $node.ident result = $node.ident
of nnkStrLit: of nnkStrLit:
result = node.strval result = node.strVal
else: else:
badNodeKind node.kind, "$" badNodeKind node.kind, "$"
@ -657,7 +657,7 @@ template findChild*(n: PNimrodNode; cond: expr): PNimrodNode {.immediate, dirty.
break break
result result
proc insert*(a: PNimrodNOde; pos: int; b: PNimrodNode) {.compileTime.} = proc insert*(a: PNimrodNode; pos: int; b: PNimrodNode) {.compileTime.} =
## Insert node B into A at pos ## Insert node B into A at pos
if high(a) < pos: if high(a) < pos:
## add some empty nodes first ## add some empty nodes first
@ -678,14 +678,14 @@ proc basename*(a: PNimrodNode): PNimrodNode {.compiletime.} =
of nnkIdent: return a of nnkIdent: return a
of nnkPostfix, nnkPrefix: return a[1] of nnkPostfix, nnkPrefix: return a[1]
else: else:
quit "Do not know how to get basename of ("& treerepr(a) &")\n"& repr(a) quit "Do not know how to get basename of ("& treeRepr(a) &")\n"& repr(a)
proc `basename=`*(a: PNimrodNode; val: string) {.compileTime.}= proc `basename=`*(a: PNimrodNode; val: string) {.compileTime.}=
case a.kind case a.kind
of nnkIdent: macros.`ident=`(a, !val) of nnkIdent: macros.`ident=`(a, !val)
of nnkPostfix, nnkPrefix: a[1] = ident(val) of nnkPostfix, nnkPrefix: a[1] = ident(val)
else: else:
quit "Do not know how to get basename of ("& treerepr(a)& ")\n"& repr(a) quit "Do not know how to get basename of ("& treeRepr(a)& ")\n"& repr(a)
proc postfix*(node: PNimrodNode; op: string): PNimrodNode {.compileTime.} = proc postfix*(node: PNimrodNode; op: string): PNimrodNode {.compileTime.} =
newNimNode(nnkPostfix).add(ident(op), node) newNimNode(nnkPostfix).add(ident(op), node)

View file

@ -28,7 +28,7 @@ const
## More subpatterns cannot be captured! ## More subpatterns cannot be captured!
type type
TRegExFlag* = enum ## options for regular expressions TRegexFlag* = enum ## options for regular expressions
reIgnoreCase = 0, ## do caseless matching reIgnoreCase = 0, ## do caseless matching
reMultiLine = 1, ## ``^`` and ``$`` match newlines within data reMultiLine = 1, ## ``^`` and ``$`` match newlines within data
reDotAll = 2, ## ``.`` matches anything including NL reDotAll = 2, ## ``.`` matches anything including NL
@ -36,11 +36,11 @@ type
reStudy = 4 ## study the expression (may be omitted if the reStudy = 4 ## study the expression (may be omitted if the
## expression will be used only once) ## expression will be used only once)
TRegExDesc {.pure, final.} = object TRegexDesc {.pure, final.} = object
h: PPcre h: PPcre
e: ptr TExtra e: ptr TExtra
TRegEx* = ref TRegExDesc ## a compiled regular expression TRegex* = ref TRegexDesc ## a compiled regular expression
EInvalidRegEx* = object of EInvalidValue EInvalidRegEx* = object of EInvalidValue
## is raised if the pattern is no valid regular expression. ## is raised if the pattern is no valid regular expression.
@ -53,13 +53,13 @@ proc raiseInvalidRegex(msg: string) {.noinline, noreturn.} =
proc rawCompile(pattern: string, flags: cint): PPcre = proc rawCompile(pattern: string, flags: cint): PPcre =
var var
msg: CString msg: cstring
offset: cint offset: cint
result = pcre.Compile(pattern, flags, addr(msg), addr(offset), nil) result = pcre.Compile(pattern, flags, addr(msg), addr(offset), nil)
if result == nil: if result == nil:
raiseInvalidRegEx($msg & "\n" & pattern & "\n" & repeatChar(offset) & "^\n") raiseInvalidRegex($msg & "\n" & pattern & "\n" & repeatChar(offset) & "^\n")
proc finalizeRegEx(x: TRegEx) = proc finalizeRegEx(x: TRegex) =
# XXX This is a hack, but PCRE does not export its "free" function properly. # XXX This is a hack, but PCRE does not export its "free" function properly.
# Sigh. The hack relies on PCRE's implementation (see ``pcre_get.c``). # Sigh. The hack relies on PCRE's implementation (see ``pcre_get.c``).
# Fortunately the implementation is unlikely to change. # Fortunately the implementation is unlikely to change.
@ -67,7 +67,7 @@ proc finalizeRegEx(x: TRegEx) =
if not isNil(x.e): if not isNil(x.e):
pcre.free_substring(cast[cstring](x.e)) pcre.free_substring(cast[cstring](x.e))
proc re*(s: string, flags = {reExtended, reStudy}): TRegEx = proc re*(s: string, flags = {reExtended, reStudy}): TRegex =
## Constructor of regular expressions. Note that Nimrod's ## Constructor of regular expressions. Note that Nimrod's
## extended raw string literals support this syntax ``re"[abc]"`` as ## extended raw string literals support this syntax ``re"[abc]"`` as
## a short form for ``re(r"[abc]")``. ## a short form for ``re(r"[abc]")``.
@ -78,7 +78,7 @@ proc re*(s: string, flags = {reExtended, reStudy}): TRegEx =
result.e = pcre.study(result.h, 0, msg) result.e = pcre.study(result.h, 0, msg)
if not isNil(msg): raiseInvalidRegex($msg) if not isNil(msg): raiseInvalidRegex($msg)
proc matchOrFind(s: string, pattern: TRegEx, matches: var openarray[string], proc matchOrFind(s: string, pattern: TRegex, matches: var openArray[string],
start, flags: cint): cint = start, flags: cint): cint =
var var
rawMatches: array[0..maxSubpatterns * 3 - 1, cint] rawMatches: array[0..maxSubpatterns * 3 - 1, cint]
@ -92,7 +92,7 @@ proc matchOrFind(s: string, pattern: TRegEx, matches: var openarray[string],
else: matches[i-1] = "" else: matches[i-1] = ""
return rawMatches[1] - rawMatches[0] return rawMatches[1] - rawMatches[0]
proc findBounds*(s: string, pattern: TRegEx, matches: var openarray[string], proc findBounds*(s: string, pattern: TRegex, matches: var openArray[string],
start = 0): tuple[first, last: int] = start = 0): tuple[first, last: int] =
## returns the starting position and end position of `pattern` in `s` ## returns the starting position and end position of `pattern` in `s`
## and the captured ## and the captured
@ -110,8 +110,8 @@ proc findBounds*(s: string, pattern: TRegEx, matches: var openarray[string],
else: matches[i-1] = "" else: matches[i-1] = ""
return (rawMatches[0].int, rawMatches[1].int - 1) return (rawMatches[0].int, rawMatches[1].int - 1)
proc findBounds*(s: string, pattern: TRegEx, proc findBounds*(s: string, pattern: TRegex,
matches: var openarray[tuple[first, last: int]], matches: var openArray[tuple[first, last: int]],
start = 0): tuple[first, last: int] = start = 0): tuple[first, last: int] =
## returns the starting position and end position of ``pattern`` in ``s`` ## returns the starting position and end position of ``pattern`` in ``s``
## and the captured substrings in the array `matches`. ## and the captured substrings in the array `matches`.
@ -129,7 +129,7 @@ proc findBounds*(s: string, pattern: TRegEx,
else: matches[i-1] = (-1,0) else: matches[i-1] = (-1,0)
return (rawMatches[0].int, rawMatches[1].int - 1) return (rawMatches[0].int, rawMatches[1].int - 1)
proc findBounds*(s: string, pattern: TRegEx, proc findBounds*(s: string, pattern: TRegex,
start = 0): tuple[first, last: int] = start = 0): tuple[first, last: int] =
## returns the starting position of `pattern` in `s`. If it does not ## returns the starting position of `pattern` in `s`. If it does not
## match, ``(-1,0)`` is returned. ## match, ``(-1,0)`` is returned.
@ -140,14 +140,14 @@ proc findBounds*(s: string, pattern: TRegEx,
if res < 0'i32: return (int(res), 0) if res < 0'i32: return (int(res), 0)
return (int(rawMatches[0]), int(rawMatches[1]-1)) return (int(rawMatches[0]), int(rawMatches[1]-1))
proc matchOrFind(s: string, pattern: TRegEx, start, flags: cint): cint = proc matchOrFind(s: string, pattern: TRegex, start, flags: cint): cint =
var rawMatches: array [0..maxSubpatterns * 3 - 1, cint] var rawMatches: array [0..maxSubpatterns * 3 - 1, cint]
result = pcre.Exec(pattern.h, pattern.e, s, len(s).cint, start, flags, result = pcre.Exec(pattern.h, pattern.e, s, len(s).cint, start, flags,
cast[ptr cint](addr(rawMatches)), maxSubpatterns * 3) cast[ptr cint](addr(rawMatches)), maxSubpatterns * 3)
if result >= 0'i32: if result >= 0'i32:
result = rawMatches[1] - rawMatches[0] result = rawMatches[1] - rawMatches[0]
proc match*(s: string, pattern: TRegEx, matches: var openarray[string], proc match*(s: string, pattern: TRegex, matches: var openArray[string],
start = 0): bool = start = 0): bool =
## returns ``true`` if ``s[start..]`` matches the ``pattern`` and ## returns ``true`` if ``s[start..]`` matches the ``pattern`` and
## the captured substrings in the array ``matches``. If it does not ## the captured substrings in the array ``matches``. If it does not
@ -156,24 +156,24 @@ proc match*(s: string, pattern: TRegEx, matches: var openarray[string],
return matchOrFind(s, pattern, matches, start.cint, return matchOrFind(s, pattern, matches, start.cint,
pcre.ANCHORED) == cint(s.len - start) pcre.ANCHORED) == cint(s.len - start)
proc match*(s: string, pattern: TRegEx, start = 0): bool = proc match*(s: string, pattern: TRegex, start = 0): bool =
## returns ``true`` if ``s[start..]`` matches the ``pattern``. ## returns ``true`` if ``s[start..]`` matches the ``pattern``.
return matchOrFind(s, pattern, start.cint, pcre.ANCHORED) == cint(s.len-start) return matchOrFind(s, pattern, start.cint, pcre.ANCHORED) == cint(s.len-start)
proc matchLen*(s: string, pattern: TRegEx, matches: var openarray[string], proc matchLen*(s: string, pattern: TRegex, matches: var openArray[string],
start = 0): int = start = 0): int =
## the same as ``match``, but it returns the length of the match, ## the same as ``match``, but it returns the length of the match,
## if there is no match, -1 is returned. Note that a match length ## if there is no match, -1 is returned. Note that a match length
## of zero can happen. ## of zero can happen.
return matchOrFind(s, pattern, matches, start.cint, pcre.ANCHORED) return matchOrFind(s, pattern, matches, start.cint, pcre.ANCHORED)
proc matchLen*(s: string, pattern: TRegEx, start = 0): int = proc matchLen*(s: string, pattern: TRegex, start = 0): int =
## the same as ``match``, but it returns the length of the match, ## the same as ``match``, but it returns the length of the match,
## if there is no match, -1 is returned. Note that a match length ## if there is no match, -1 is returned. Note that a match length
## of zero can happen. ## of zero can happen.
return matchOrFind(s, pattern, start.cint, pcre.ANCHORED) return matchOrFind(s, pattern, start.cint, pcre.ANCHORED)
proc find*(s: string, pattern: TRegEx, matches: var openarray[string], proc find*(s: string, pattern: TRegex, matches: var openArray[string],
start = 0): int = start = 0): int =
## returns the starting position of ``pattern`` in ``s`` and the captured ## returns the starting position of ``pattern`` in ``s`` and the captured
## substrings in the array ``matches``. If it does not match, nothing ## substrings in the array ``matches``. If it does not match, nothing
@ -190,7 +190,7 @@ proc find*(s: string, pattern: TRegEx, matches: var openarray[string],
else: matches[i-1] = "" else: matches[i-1] = ""
return rawMatches[0] return rawMatches[0]
proc find*(s: string, pattern: TRegEx, start = 0): int = proc find*(s: string, pattern: TRegex, start = 0): int =
## returns the starting position of ``pattern`` in ``s``. If it does not ## returns the starting position of ``pattern`` in ``s``. If it does not
## match, -1 is returned. ## match, -1 is returned.
var var
@ -200,7 +200,7 @@ proc find*(s: string, pattern: TRegEx, start = 0): int =
if res < 0'i32: return res if res < 0'i32: return res
return rawMatches[0] return rawMatches[0]
iterator findAll*(s: string, pattern: TRegEx, start = 0): string = iterator findAll*(s: string, pattern: TRegex, start = 0): string =
## Yields all matching *substrings* of `s` that match `pattern`. ## Yields all matching *substrings* of `s` that match `pattern`.
## ##
## Note that since this is an iterator you should not modify the string you ## Note that since this is an iterator you should not modify the string you
@ -216,7 +216,7 @@ iterator findAll*(s: string, pattern: TRegEx, start = 0): string =
yield substr(s, int(a), int(b)-1) yield substr(s, int(a), int(b)-1)
i = b i = b
proc findAll*(s: string, pattern: TRegEx, start = 0): seq[string] = proc findAll*(s: string, pattern: TRegex, start = 0): seq[string] =
## returns all matching *substrings* of `s` that match `pattern`. ## returns all matching *substrings* of `s` that match `pattern`.
## If it does not match, @[] is returned. ## If it does not match, @[] is returned.
accumulateResult(findAll(s, pattern, start)) accumulateResult(findAll(s, pattern, start))
@ -224,7 +224,7 @@ proc findAll*(s: string, pattern: TRegEx, start = 0): seq[string] =
when not defined(nimhygiene): when not defined(nimhygiene):
{.pragma: inject.} {.pragma: inject.}
template `=~` *(s: string, pattern: TRegEx): expr = template `=~` *(s: string, pattern: TRegex): expr =
## This calls ``match`` with an implicit declared ``matches`` array that ## This calls ``match`` with an implicit declared ``matches`` array that
## can be used in the scope of the ``=~`` call: ## can be used in the scope of the ``=~`` call:
## ##
@ -244,30 +244,30 @@ template `=~` *(s: string, pattern: TRegEx): expr =
## ##
bind maxSubPatterns bind maxSubPatterns
when not definedInScope(matches): when not definedInScope(matches):
var matches {.inject.}: array[0..maxSubPatterns-1, string] var matches {.inject.}: array[0..MaxSubpatterns-1, string]
match(s, pattern, matches) match(s, pattern, matches)
# ------------------------- more string handling ------------------------------ # ------------------------- more string handling ------------------------------
proc contains*(s: string, pattern: TRegEx, start = 0): bool = proc contains*(s: string, pattern: TRegex, start = 0): bool =
## same as ``find(s, pattern, start) >= 0`` ## same as ``find(s, pattern, start) >= 0``
return find(s, pattern, start) >= 0 return find(s, pattern, start) >= 0
proc contains*(s: string, pattern: TRegEx, matches: var openArray[string], proc contains*(s: string, pattern: TRegex, matches: var openArray[string],
start = 0): bool = start = 0): bool =
## same as ``find(s, pattern, matches, start) >= 0`` ## same as ``find(s, pattern, matches, start) >= 0``
return find(s, pattern, matches, start) >= 0 return find(s, pattern, matches, start) >= 0
proc startsWith*(s: string, prefix: TRegEx): bool = proc startsWith*(s: string, prefix: TRegex): bool =
## returns true if `s` starts with the pattern `prefix` ## returns true if `s` starts with the pattern `prefix`
result = matchLen(s, prefix) >= 0 result = matchLen(s, prefix) >= 0
proc endsWith*(s: string, suffix: TRegEx): bool = proc endsWith*(s: string, suffix: TRegex): bool =
## returns true if `s` ends with the pattern `prefix` ## returns true if `s` ends with the pattern `prefix`
for i in 0 .. s.len-1: for i in 0 .. s.len-1:
if matchLen(s, suffix, i) == s.len - i: return true if matchLen(s, suffix, i) == s.len - i: return true
proc replace*(s: string, sub: TRegEx, by = ""): string = proc replace*(s: string, sub: TRegex, by = ""): string =
## Replaces `sub` in `s` by the string `by`. Captures cannot be ## Replaces `sub` in `s` by the string `by`. Captures cannot be
## accessed in `by`. Examples: ## accessed in `by`. Examples:
## ##
@ -289,7 +289,7 @@ proc replace*(s: string, sub: TRegEx, by = ""): string =
prev = match.last + 1 prev = match.last + 1
add(result, substr(s, prev)) add(result, substr(s, prev))
proc replacef*(s: string, sub: TRegEx, by: string): string = proc replacef*(s: string, sub: TRegex, by: string): string =
## Replaces `sub` in `s` by the string `by`. Captures can be accessed in `by` ## Replaces `sub` in `s` by the string `by`. Captures can be accessed in `by`
## with the notation ``$i`` and ``$#`` (see strutils.`%`). Examples: ## with the notation ``$i`` and ``$#`` (see strutils.`%`). Examples:
## ##
@ -327,7 +327,7 @@ proc replacef*(s: string, sub: TRegEx, by: string): string =
add(result, substr(s, i)) add(result, substr(s, i))
proc parallelReplace*(s: string, subs: openArray[ proc parallelReplace*(s: string, subs: openArray[
tuple[pattern: TRegEx, repl: string]]): string = tuple[pattern: TRegex, repl: string]]): string =
## Returns a modified copy of `s` with the substitutions in `subs` ## Returns a modified copy of `s` with the substitutions in `subs`
## applied in parallel. ## applied in parallel.
result = "" result = ""
@ -347,14 +347,14 @@ proc parallelReplace*(s: string, subs: openArray[
add(result, substr(s, i)) add(result, substr(s, i))
proc transformFile*(infile, outfile: string, proc transformFile*(infile, outfile: string,
subs: openArray[tuple[pattern: TRegEx, repl: string]]) = subs: openArray[tuple[pattern: TRegex, repl: string]]) =
## reads in the file `infile`, performs a parallel replacement (calls ## reads in the file `infile`, performs a parallel replacement (calls
## `parallelReplace`) and writes back to `outfile`. Raises ``EIO`` if an ## `parallelReplace`) and writes back to `outfile`. Raises ``EIO`` if an
## error occurs. This is supposed to be used for quick scripting. ## error occurs. This is supposed to be used for quick scripting.
var x = readFile(infile).string var x = readFile(infile).string
writeFile(outfile, x.parallelReplace(subs)) writeFile(outfile, x.parallelReplace(subs))
iterator split*(s: string, sep: TRegEx): string = iterator split*(s: string, sep: TRegex): string =
## Splits the string `s` into substrings. ## Splits the string `s` into substrings.
## ##
## Substrings are separated by the regular expression `sep`. ## Substrings are separated by the regular expression `sep`.
@ -386,7 +386,7 @@ iterator split*(s: string, sep: TRegEx): string =
if first < last: if first < last:
yield substr(s, first, last-1) yield substr(s, first, last-1)
proc split*(s: string, sep: TRegEx): seq[string] = proc split*(s: string, sep: TRegex): seq[string] =
## Splits the string `s` into substrings. ## Splits the string `s` into substrings.
accumulateResult(split(s, sep)) accumulateResult(split(s, sep))

View file

@ -249,23 +249,23 @@ proc newLine*: TPeg {.inline.} =
## constructs the PEG `newline`:idx: (``\n``) ## constructs the PEG `newline`:idx: (``\n``)
result.kind = pkNewline result.kind = pkNewline
proc UnicodeLetter*: TPeg {.inline.} = proc unicodeLetter*: TPeg {.inline.} =
## constructs the PEG ``\letter`` which matches any Unicode letter. ## constructs the PEG ``\letter`` which matches any Unicode letter.
result.kind = pkLetter result.kind = pkLetter
proc UnicodeLower*: TPeg {.inline.} = proc unicodeLower*: TPeg {.inline.} =
## constructs the PEG ``\lower`` which matches any Unicode lowercase letter. ## constructs the PEG ``\lower`` which matches any Unicode lowercase letter.
result.kind = pkLower result.kind = pkLower
proc UnicodeUpper*: TPeg {.inline.} = proc unicodeUpper*: TPeg {.inline.} =
## constructs the PEG ``\upper`` which matches any Unicode uppercase letter. ## constructs the PEG ``\upper`` which matches any Unicode uppercase letter.
result.kind = pkUpper result.kind = pkUpper
proc UnicodeTitle*: TPeg {.inline.} = proc unicodeTitle*: TPeg {.inline.} =
## constructs the PEG ``\title`` which matches any Unicode title letter. ## constructs the PEG ``\title`` which matches any Unicode title letter.
result.kind = pkTitle result.kind = pkTitle
proc UnicodeWhitespace*: TPeg {.inline.} = proc unicodeWhitespace*: TPeg {.inline.} =
## constructs the PEG ``\white`` which matches any Unicode ## constructs the PEG ``\white`` which matches any Unicode
## whitespace character. ## whitespace character.
result.kind = pkWhitespace result.kind = pkWhitespace
@ -340,28 +340,28 @@ proc newNonTerminal*(name: string, line, column: int): PNonTerminal {.
template letters*: expr = template letters*: expr =
## expands to ``charset({'A'..'Z', 'a'..'z'})`` ## expands to ``charset({'A'..'Z', 'a'..'z'})``
charset({'A'..'Z', 'a'..'z'}) charSet({'A'..'Z', 'a'..'z'})
template digits*: expr = template digits*: expr =
## expands to ``charset({'0'..'9'})`` ## expands to ``charset({'0'..'9'})``
charset({'0'..'9'}) charSet({'0'..'9'})
template whitespace*: expr = template whitespace*: expr =
## expands to ``charset({' ', '\9'..'\13'})`` ## expands to ``charset({' ', '\9'..'\13'})``
charset({' ', '\9'..'\13'}) charSet({' ', '\9'..'\13'})
template identChars*: expr = template identChars*: expr =
## expands to ``charset({'a'..'z', 'A'..'Z', '0'..'9', '_'})`` ## expands to ``charset({'a'..'z', 'A'..'Z', '0'..'9', '_'})``
charset({'a'..'z', 'A'..'Z', '0'..'9', '_'}) charSet({'a'..'z', 'A'..'Z', '0'..'9', '_'})
template identStartChars*: expr = template identStartChars*: expr =
## expands to ``charset({'A'..'Z', 'a'..'z', '_'})`` ## expands to ``charset({'A'..'Z', 'a'..'z', '_'})``
charset({'a'..'z', 'A'..'Z', '_'}) charSet({'a'..'z', 'A'..'Z', '_'})
template ident*: expr = template ident*: expr =
## same as ``[a-zA-Z_][a-zA-z_0-9]*``; standard identifier ## same as ``[a-zA-Z_][a-zA-z_0-9]*``; standard identifier
sequence(charset({'a'..'z', 'A'..'Z', '_'}), sequence(charSet({'a'..'z', 'A'..'Z', '_'}),
*charset({'a'..'z', 'A'..'Z', '0'..'9', '_'})) *charSet({'a'..'z', 'A'..'Z', '0'..'9', '_'}))
template natural*: expr = template natural*: expr =
## same as ``\d+`` ## same as ``\d+``
@ -385,7 +385,7 @@ proc esc(c: char, reserved = {'\0'..'\255'}): string =
elif c in reserved: result = '\\' & c elif c in reserved: result = '\\' & c
else: result = $c else: result = $c
proc singleQuoteEsc(c: Char): string = return "'" & esc(c, {'\''}) & "'" proc singleQuoteEsc(c: char): string = return "'" & esc(c, {'\''}) & "'"
proc singleQuoteEsc(str: string): string = proc singleQuoteEsc(str: string): string =
result = "'" result = "'"
@ -409,11 +409,11 @@ proc charSetEscAux(cc: set[char]): string =
c1 = c2 c1 = c2
inc(c1) inc(c1)
proc CharSetEsc(cc: set[char]): string = proc charSetEsc(cc: set[char]): string =
if card(cc) >= 128+64: if card(cc) >= 128+64:
result = "[^" & CharSetEscAux({'\1'..'\xFF'} - cc) & ']' result = "[^" & charSetEscAux({'\1'..'\xFF'} - cc) & ']'
else: else:
result = '[' & CharSetEscAux(cc) & ']' result = '[' & charSetEscAux(cc) & ']'
proc toStrAux(r: TPeg, res: var string) = proc toStrAux(r: TPeg, res: var string) =
case r.kind case r.kind
@ -590,7 +590,7 @@ proc rawMatch*(s: string, p: TPeg, start: int, c: var TCaptures): int {.
var a: TRune var a: TRune
result = start result = start
fastRuneAt(s, result, a) fastRuneAt(s, result, a)
if isWhitespace(a): dec(result, start) if isWhiteSpace(a): dec(result, start)
else: result = -1 else: result = -1
else: else:
result = -1 result = -1
@ -747,7 +747,7 @@ template fillMatches(s, caps, c: expr) =
for k in 0..c.ml-1: for k in 0..c.ml-1:
caps[k] = substr(s, c.matches[k][0], c.matches[k][1]) caps[k] = substr(s, c.matches[k][0], c.matches[k][1])
proc match*(s: string, pattern: TPeg, matches: var openarray[string], proc match*(s: string, pattern: TPeg, matches: var openArray[string],
start = 0): bool {.nosideEffect, rtl, extern: "npegs$1Capture".} = start = 0): bool {.nosideEffect, rtl, extern: "npegs$1Capture".} =
## returns ``true`` if ``s[start..]`` matches the ``pattern`` and ## returns ``true`` if ``s[start..]`` matches the ``pattern`` and
## the captured substrings in the array ``matches``. If it does not ## the captured substrings in the array ``matches``. If it does not
@ -765,7 +765,7 @@ proc match*(s: string, pattern: TPeg,
c.origStart = start c.origStart = start
result = rawMatch(s, pattern, start, c) == len(s)-start result = rawMatch(s, pattern, start, c) == len(s)-start
proc matchLen*(s: string, pattern: TPeg, matches: var openarray[string], proc matchLen*(s: string, pattern: TPeg, matches: var openArray[string],
start = 0): int {.nosideEffect, rtl, extern: "npegs$1Capture".} = start = 0): int {.nosideEffect, rtl, extern: "npegs$1Capture".} =
## the same as ``match``, but it returns the length of the match, ## the same as ``match``, but it returns the length of the match,
## if there is no match, -1 is returned. Note that a match length ## if there is no match, -1 is returned. Note that a match length
@ -786,7 +786,7 @@ proc matchLen*(s: string, pattern: TPeg,
c.origStart = start c.origStart = start
result = rawMatch(s, pattern, start, c) result = rawMatch(s, pattern, start, c)
proc find*(s: string, pattern: TPeg, matches: var openarray[string], proc find*(s: string, pattern: TPeg, matches: var openArray[string],
start = 0): int {.nosideEffect, rtl, extern: "npegs$1Capture".} = start = 0): int {.nosideEffect, rtl, extern: "npegs$1Capture".} =
## returns the starting position of ``pattern`` in ``s`` and the captured ## returns the starting position of ``pattern`` in ``s`` and the captured
## substrings in the array ``matches``. If it does not match, nothing ## substrings in the array ``matches``. If it does not match, nothing
@ -801,7 +801,7 @@ proc find*(s: string, pattern: TPeg, matches: var openarray[string],
return -1 return -1
# could also use the pattern here: (!P .)* P # could also use the pattern here: (!P .)* P
proc findBounds*(s: string, pattern: TPeg, matches: var openarray[string], proc findBounds*(s: string, pattern: TPeg, matches: var openArray[string],
start = 0): tuple[first, last: int] {. start = 0): tuple[first, last: int] {.
nosideEffect, rtl, extern: "npegs$1Capture".} = nosideEffect, rtl, extern: "npegs$1Capture".} =
## returns the starting position and end position of ``pattern`` in ``s`` ## returns the starting position and end position of ``pattern`` in ``s``
@ -869,7 +869,7 @@ template `=~`*(s: string, pattern: TPeg): bool =
## ##
bind maxSubpatterns bind maxSubpatterns
when not definedInScope(matches): when not definedInScope(matches):
var matches {.inject.}: array[0..maxSubpatterns-1, string] var matches {.inject.}: array[0..MaxSubpatterns-1, string]
match(s, pattern, matches) match(s, pattern, matches)
# ------------------------- more string handling ------------------------------ # ------------------------- more string handling ------------------------------
@ -1074,14 +1074,14 @@ const
"@", "built-in", "escaped", "$", "$", "^" "@", "built-in", "escaped", "$", "$", "^"
] ]
proc HandleCR(L: var TPegLexer, pos: int): int = proc handleCR(L: var TPegLexer, pos: int): int =
assert(L.buf[pos] == '\c') assert(L.buf[pos] == '\c')
inc(L.linenumber) inc(L.linenumber)
result = pos+1 result = pos+1
if L.buf[result] == '\L': inc(result) if L.buf[result] == '\L': inc(result)
L.lineStart = result L.lineStart = result
proc HandleLF(L: var TPegLexer, pos: int): int = proc handleLF(L: var TPegLexer, pos: int): int =
assert(L.buf[pos] == '\L') assert(L.buf[pos] == '\L')
inc(L.linenumber) inc(L.linenumber)
result = pos+1 result = pos+1
@ -1124,38 +1124,38 @@ proc getEscapedChar(c: var TPegLexer, tok: var TToken) =
case c.buf[c.bufpos] case c.buf[c.bufpos]
of 'r', 'R', 'c', 'C': of 'r', 'R', 'c', 'C':
add(tok.literal, '\c') add(tok.literal, '\c')
Inc(c.bufpos) inc(c.bufpos)
of 'l', 'L': of 'l', 'L':
add(tok.literal, '\L') add(tok.literal, '\L')
Inc(c.bufpos) inc(c.bufpos)
of 'f', 'F': of 'f', 'F':
add(tok.literal, '\f') add(tok.literal, '\f')
inc(c.bufpos) inc(c.bufpos)
of 'e', 'E': of 'e', 'E':
add(tok.literal, '\e') add(tok.literal, '\e')
Inc(c.bufpos) inc(c.bufpos)
of 'a', 'A': of 'a', 'A':
add(tok.literal, '\a') add(tok.literal, '\a')
Inc(c.bufpos) inc(c.bufpos)
of 'b', 'B': of 'b', 'B':
add(tok.literal, '\b') add(tok.literal, '\b')
Inc(c.bufpos) inc(c.bufpos)
of 'v', 'V': of 'v', 'V':
add(tok.literal, '\v') add(tok.literal, '\v')
Inc(c.bufpos) inc(c.bufpos)
of 't', 'T': of 't', 'T':
add(tok.literal, '\t') add(tok.literal, '\t')
Inc(c.bufpos) inc(c.bufpos)
of 'x', 'X': of 'x', 'X':
inc(c.bufpos) inc(c.bufpos)
var xi = 0 var xi = 0
handleHexChar(c, xi) handleHexChar(c, xi)
handleHexChar(c, xi) handleHexChar(c, xi)
if xi == 0: tok.kind = tkInvalid if xi == 0: tok.kind = tkInvalid
else: add(tok.literal, Chr(xi)) else: add(tok.literal, chr(xi))
of '0'..'9': of '0'..'9':
var val = ord(c.buf[c.bufpos]) - ord('0') var val = ord(c.buf[c.bufpos]) - ord('0')
Inc(c.bufpos) inc(c.bufpos)
var i = 1 var i = 1
while (i <= 3) and (c.buf[c.bufpos] in {'0'..'9'}): while (i <= 3) and (c.buf[c.bufpos] in {'0'..'9'}):
val = val * 10 + ord(c.buf[c.bufpos]) - ord('0') val = val * 10 + ord(c.buf[c.bufpos]) - ord('0')
@ -1169,7 +1169,7 @@ proc getEscapedChar(c: var TPegLexer, tok: var TToken) =
tok.kind = tkInvalid tok.kind = tkInvalid
else: else:
add(tok.literal, c.buf[c.bufpos]) add(tok.literal, c.buf[c.bufpos])
Inc(c.bufpos) inc(c.bufpos)
proc skip(c: var TPegLexer) = proc skip(c: var TPegLexer) =
var pos = c.bufpos var pos = c.bufpos
@ -1177,14 +1177,14 @@ proc skip(c: var TPegLexer) =
while true: while true:
case buf[pos] case buf[pos]
of ' ', '\t': of ' ', '\t':
Inc(pos) inc(pos)
of '#': of '#':
while not (buf[pos] in {'\c', '\L', '\0'}): inc(pos) while not (buf[pos] in {'\c', '\L', '\0'}): inc(pos)
of '\c': of '\c':
pos = HandleCR(c, pos) pos = handleCR(c, pos)
buf = c.buf buf = c.buf
of '\L': of '\L':
pos = HandleLF(c, pos) pos = handleLF(c, pos)
buf = c.buf buf = c.buf
else: else:
break # EndOfFile also leaves the loop break # EndOfFile also leaves the loop
@ -1209,7 +1209,7 @@ proc getString(c: var TPegLexer, tok: var TToken) =
break break
else: else:
add(tok.literal, buf[pos]) add(tok.literal, buf[pos])
Inc(pos) inc(pos)
c.bufpos = pos c.bufpos = pos
proc getDollar(c: var TPegLexer, tok: var TToken) = proc getDollar(c: var TPegLexer, tok: var TToken) =
@ -1250,7 +1250,7 @@ proc getCharSet(c: var TPegLexer, tok: var TToken) =
break break
else: else:
ch = buf[pos] ch = buf[pos]
Inc(pos) inc(pos)
incl(tok.charset, ch) incl(tok.charset, ch)
if buf[pos] == '-': if buf[pos] == '-':
if buf[pos+1] == ']': if buf[pos+1] == ']':
@ -1270,7 +1270,7 @@ proc getCharSet(c: var TPegLexer, tok: var TToken) =
break break
else: else:
ch2 = buf[pos] ch2 = buf[pos]
Inc(pos) inc(pos)
for i in ord(ch)+1 .. ord(ch2): for i in ord(ch)+1 .. ord(ch2):
incl(tok.charset, chr(i)) incl(tok.charset, chr(i))
c.bufpos = pos c.bufpos = pos
@ -1281,7 +1281,7 @@ proc getSymbol(c: var TPegLexer, tok: var TToken) =
var buf = c.buf var buf = c.buf
while true: while true:
add(tok.literal, buf[pos]) add(tok.literal, buf[pos])
Inc(pos) inc(pos)
if buf[pos] notin strutils.IdentChars: break if buf[pos] notin strutils.IdentChars: break
c.bufpos = pos c.bufpos = pos
tok.kind = tkIdentifier tok.kind = tkIdentifier
@ -1298,7 +1298,7 @@ proc getBuiltin(c: var TPegLexer, tok: var TToken) =
proc getTok(c: var TPegLexer, tok: var TToken) = proc getTok(c: var TPegLexer, tok: var TToken) =
tok.kind = tkInvalid tok.kind = tkInvalid
tok.modifier = modNone tok.modifier = modNone
setlen(tok.literal, 0) setLen(tok.literal, 0)
skip(c) skip(c)
case c.buf[c.bufpos] case c.buf[c.bufpos]
of '{': of '{':
@ -1315,14 +1315,14 @@ proc getTok(c: var TPegLexer, tok: var TToken) =
inc(c.bufpos) inc(c.bufpos)
add(tok.literal, '}') add(tok.literal, '}')
of '[': of '[':
getCharset(c, tok) getCharSet(c, tok)
of '(': of '(':
tok.kind = tkParLe tok.kind = tkParLe
Inc(c.bufpos) inc(c.bufpos)
add(tok.literal, '(') add(tok.literal, '(')
of ')': of ')':
tok.kind = tkParRi tok.kind = tkParRi
Inc(c.bufpos) inc(c.bufpos)
add(tok.literal, ')') add(tok.literal, ')')
of '.': of '.':
tok.kind = tkAny tok.kind = tkAny
@ -1452,28 +1452,28 @@ proc modifiedTerm(s: string, m: TModifier): TPeg =
proc modifiedBackref(s: int, m: TModifier): TPeg = proc modifiedBackref(s: int, m: TModifier): TPeg =
case m case m
of modNone, modVerbatim: result = backRef(s) of modNone, modVerbatim: result = backref(s)
of modIgnoreCase: result = backRefIgnoreCase(s) of modIgnoreCase: result = backrefIgnoreCase(s)
of modIgnoreStyle: result = backRefIgnoreStyle(s) of modIgnoreStyle: result = backrefIgnoreStyle(s)
proc builtin(p: var TPegParser): TPeg = proc builtin(p: var TPegParser): TPeg =
# do not use "y", "skip" or "i" as these would be ambiguous # do not use "y", "skip" or "i" as these would be ambiguous
case p.tok.literal case p.tok.literal
of "n": result = newLine() of "n": result = newLine()
of "d": result = charset({'0'..'9'}) of "d": result = charSet({'0'..'9'})
of "D": result = charset({'\1'..'\xff'} - {'0'..'9'}) of "D": result = charSet({'\1'..'\xff'} - {'0'..'9'})
of "s": result = charset({' ', '\9'..'\13'}) of "s": result = charSet({' ', '\9'..'\13'})
of "S": result = charset({'\1'..'\xff'} - {' ', '\9'..'\13'}) of "S": result = charSet({'\1'..'\xff'} - {' ', '\9'..'\13'})
of "w": result = charset({'a'..'z', 'A'..'Z', '_', '0'..'9'}) of "w": result = charSet({'a'..'z', 'A'..'Z', '_', '0'..'9'})
of "W": result = charset({'\1'..'\xff'} - {'a'..'z','A'..'Z','_','0'..'9'}) of "W": result = charSet({'\1'..'\xff'} - {'a'..'z','A'..'Z','_','0'..'9'})
of "a": result = charset({'a'..'z', 'A'..'Z'}) of "a": result = charSet({'a'..'z', 'A'..'Z'})
of "A": result = charset({'\1'..'\xff'} - {'a'..'z', 'A'..'Z'}) of "A": result = charSet({'\1'..'\xff'} - {'a'..'z', 'A'..'Z'})
of "ident": result = pegs.ident of "ident": result = pegs.ident
of "letter": result = UnicodeLetter() of "letter": result = unicodeLetter()
of "upper": result = UnicodeUpper() of "upper": result = unicodeUpper()
of "lower": result = UnicodeLower() of "lower": result = unicodeLower()
of "title": result = UnicodeTitle() of "title": result = unicodeTitle()
of "white": result = UnicodeWhitespace() of "white": result = unicodeWhitespace()
else: pegError(p, "unknown built-in: " & p.tok.literal) else: pegError(p, "unknown built-in: " & p.tok.literal)
proc token(terminal: TPeg, p: TPegParser): TPeg = proc token(terminal: TPeg, p: TPegParser): TPeg =
@ -1505,7 +1505,7 @@ proc primary(p: var TPegParser): TPeg =
elif not arrowIsNextTok(p): elif not arrowIsNextTok(p):
var nt = getNonTerminal(p, p.tok.literal) var nt = getNonTerminal(p, p.tok.literal)
incl(nt.flags, ntUsed) incl(nt.flags, ntUsed)
result = nonTerminal(nt).token(p) result = nonterminal(nt).token(p)
getTok(p) getTok(p)
else: else:
pegError(p, "expression expected, but found: " & p.tok.literal) pegError(p, "expression expected, but found: " & p.tok.literal)
@ -1517,7 +1517,7 @@ proc primary(p: var TPegParser): TPeg =
of tkCharSet: of tkCharSet:
if '\0' in p.tok.charset: if '\0' in p.tok.charset:
pegError(p, "binary zero ('\\0') not allowed in character class") pegError(p, "binary zero ('\\0') not allowed in character class")
result = charset(p.tok.charset).token(p) result = charSet(p.tok.charset).token(p)
getTok(p) getTok(p)
of tkParLe: of tkParLe:
getTok(p) getTok(p)
@ -1549,7 +1549,7 @@ proc primary(p: var TPegParser): TPeg =
of tkBackref: of tkBackref:
var m = p.tok.modifier var m = p.tok.modifier
if m == modNone: m = p.modifier if m == modNone: m = p.modifier
result = modifiedBackRef(p.tok.index, m).token(p) result = modifiedBackref(p.tok.index, m).token(p)
if p.tok.index < 0 or p.tok.index > p.captures: if p.tok.index < 0 or p.tok.index > p.captures:
pegError(p, "invalid back reference index: " & $p.tok.index) pegError(p, "invalid back reference index: " & $p.tok.index)
getTok(p) getTok(p)

View file

@ -27,15 +27,15 @@ when defined(windows):
var hTemp = GetStdHandle(STD_OUTPUT_HANDLE) var hTemp = GetStdHandle(STD_OUTPUT_HANDLE)
if DuplicateHandle(GetCurrentProcess(), hTemp, GetCurrentProcess(), if DuplicateHandle(GetCurrentProcess(), hTemp, GetCurrentProcess(),
addr(conHandle), 0, 1, DUPLICATE_SAME_ACCESS) == 0: addr(conHandle), 0, 1, DUPLICATE_SAME_ACCESS) == 0:
OSError(OSLastError()) osError(osLastError())
proc getCursorPos(): tuple [x,y: int] = proc getCursorPos(): tuple [x,y: int] =
var c: TCONSOLE_SCREEN_BUFFER_INFO var c: TCONSOLESCREENBUFFERINFO
if GetConsoleScreenBufferInfo(conHandle, addr(c)) == 0: OSError(OSLastError()) if GetConsoleScreenBufferInfo(conHandle, addr(c)) == 0: osError(osLastError())
return (int(c.dwCursorPosition.x), int(c.dwCursorPosition.y)) return (int(c.dwCursorPosition.x), int(c.dwCursorPosition.y))
proc getAttributes(): int16 = proc getAttributes(): int16 =
var c: TCONSOLE_SCREEN_BUFFER_INFO var c: TCONSOLESCREENBUFFERINFO
# workaround Windows bugs: try several times # workaround Windows bugs: try several times
if GetConsoleScreenBufferInfo(conHandle, addr(c)) != 0: if GetConsoleScreenBufferInfo(conHandle, addr(c)) != 0:
return c.wAttributes return c.wAttributes
@ -48,10 +48,10 @@ proc setCursorPos*(x, y: int) =
## sets the terminal's cursor to the (x,y) position. (0,0) is the ## sets the terminal's cursor to the (x,y) position. (0,0) is the
## upper left of the screen. ## upper left of the screen.
when defined(windows): when defined(windows):
var c: TCoord var c: TCOORD
c.x = int16(x) c.x = int16(x)
c.y = int16(y) c.y = int16(y)
if SetConsoleCursorPosition(conHandle, c) == 0: OSError(OSLastError()) if SetConsoleCursorPosition(conHandle, c) == 0: osError(osLastError())
else: else:
stdout.write("\e[" & $y & ';' & $x & 'f') stdout.write("\e[" & $y & ';' & $x & 'f')
@ -59,12 +59,12 @@ proc setCursorXPos*(x: int) =
## sets the terminal's cursor to the x position. The y position is ## sets the terminal's cursor to the x position. The y position is
## not changed. ## not changed.
when defined(windows): when defined(windows):
var scrbuf: TCONSOLE_SCREEN_BUFFER_INFO var scrbuf: TCONSOLESCREENBUFFERINFO
var hStdout = conHandle var hStdout = conHandle
if GetConsoleScreenBufferInfo(hStdout, addr(scrbuf)) == 0: OSError(OSLastError()) if GetConsoleScreenBufferInfo(hStdout, addr(scrbuf)) == 0: osError(osLastError())
var origin = scrbuf.dwCursorPosition var origin = scrbuf.dwCursorPosition
origin.x = int16(x) origin.x = int16(x)
if SetConsoleCursorPosition(conHandle, origin) == 0: OSError(OSLastError()) if SetConsoleCursorPosition(conHandle, origin) == 0: osError(osLastError())
else: else:
stdout.write("\e[" & $x & 'G') stdout.write("\e[" & $x & 'G')
@ -73,16 +73,16 @@ when defined(windows):
## sets the terminal's cursor to the y position. The x position is ## sets the terminal's cursor to the y position. The x position is
## not changed. **Warning**: This is not supported on UNIX! ## not changed. **Warning**: This is not supported on UNIX!
when defined(windows): when defined(windows):
var scrbuf: TCONSOLE_SCREEN_BUFFER_INFO var scrbuf: TCONSOLESCREENBUFFERINFO
var hStdout = conHandle var hStdout = conHandle
if GetConsoleScreenBufferInfo(hStdout, addr(scrbuf)) == 0: OSError(OSLastError()) if GetConsoleScreenBufferInfo(hStdout, addr(scrbuf)) == 0: osError(osLastError())
var origin = scrbuf.dwCursorPosition var origin = scrbuf.dwCursorPosition
origin.y = int16(y) origin.y = int16(y)
if SetConsoleCursorPosition(conHandle, origin) == 0: OSError(OSLastError()) if SetConsoleCursorPosition(conHandle, origin) == 0: osError(osLastError())
else: else:
nil discard
proc CursorUp*(count=1) = proc cursorUp*(count=1) =
## Moves the cursor up by `count` rows. ## Moves the cursor up by `count` rows.
when defined(windows): when defined(windows):
var p = getCursorPos() var p = getCursorPos()
@ -91,7 +91,7 @@ proc CursorUp*(count=1) =
else: else:
stdout.write("\e[" & $count & 'A') stdout.write("\e[" & $count & 'A')
proc CursorDown*(count=1) = proc cursorDown*(count=1) =
## Moves the cursor down by `count` rows. ## Moves the cursor down by `count` rows.
when defined(windows): when defined(windows):
var p = getCursorPos() var p = getCursorPos()
@ -100,7 +100,7 @@ proc CursorDown*(count=1) =
else: else:
stdout.write("\e[" & $count & 'B') stdout.write("\e[" & $count & 'B')
proc CursorForward*(count=1) = proc cursorForward*(count=1) =
## Moves the cursor forward by `count` columns. ## Moves the cursor forward by `count` columns.
when defined(windows): when defined(windows):
var p = getCursorPos() var p = getCursorPos()
@ -109,7 +109,7 @@ proc CursorForward*(count=1) =
else: else:
stdout.write("\e[" & $count & 'C') stdout.write("\e[" & $count & 'C')
proc CursorBackward*(count=1) = proc cursorBackward*(count=1) =
## Moves the cursor backward by `count` columns. ## Moves the cursor backward by `count` columns.
when defined(windows): when defined(windows):
var p = getCursorPos() var p = getCursorPos()
@ -119,78 +119,78 @@ proc CursorBackward*(count=1) =
stdout.write("\e[" & $count & 'D') stdout.write("\e[" & $count & 'D')
when true: when true:
nil discard
else: else:
proc EraseLineEnd* = proc eraseLineEnd* =
## Erases from the current cursor position to the end of the current line. ## Erases from the current cursor position to the end of the current line.
when defined(windows): when defined(windows):
nil discard
else: else:
stdout.write("\e[K") stdout.write("\e[K")
proc EraseLineStart* = proc eraseLineStart* =
## Erases from the current cursor position to the start of the current line. ## Erases from the current cursor position to the start of the current line.
when defined(windows): when defined(windows):
nil discard
else: else:
stdout.write("\e[1K") stdout.write("\e[1K")
proc EraseDown* = proc eraseDown* =
## Erases the screen from the current line down to the bottom of the screen. ## Erases the screen from the current line down to the bottom of the screen.
when defined(windows): when defined(windows):
nil discard
else: else:
stdout.write("\e[J") stdout.write("\e[J")
proc EraseUp* = proc eraseUp* =
## Erases the screen from the current line up to the top of the screen. ## Erases the screen from the current line up to the top of the screen.
when defined(windows): when defined(windows):
nil discard
else: else:
stdout.write("\e[1J") stdout.write("\e[1J")
proc EraseLine* = proc eraseLine* =
## Erases the entire current line. ## Erases the entire current line.
when defined(windows): when defined(windows):
var scrbuf: TCONSOLE_SCREEN_BUFFER_INFO var scrbuf: TCONSOLESCREENBUFFERINFO
var numwrote: DWORD var numwrote: DWORD
var hStdout = conHandle var hStdout = conHandle
if GetConsoleScreenBufferInfo(hStdout, addr(scrbuf)) == 0: OSError(OSLastError()) if GetConsoleScreenBufferInfo(hStdout, addr(scrbuf)) == 0: osError(osLastError())
var origin = scrbuf.dwCursorPosition var origin = scrbuf.dwCursorPosition
origin.x = 0'i16 origin.x = 0'i16
if SetConsoleCursorPosition(conHandle, origin) == 0: OSError(OSLastError()) if SetConsoleCursorPosition(conHandle, origin) == 0: osError(osLastError())
var ht = scrbuf.dwSize.Y - origin.Y var ht = scrbuf.dwSize.Y - origin.Y
var wt = scrbuf.dwSize.X - origin.X var wt = scrbuf.dwSize.X - origin.X
if FillConsoleOutputCharacter(hStdout,' ', ht*wt, if FillConsoleOutputCharacter(hStdout,' ', ht*wt,
origin, addr(numwrote)) == 0: origin, addr(numwrote)) == 0:
OSError(OSLastError()) osError(osLastError())
if FillConsoleOutputAttribute(hStdout, scrbuf.wAttributes, ht * wt, if FillConsoleOutputAttribute(hStdout, scrbuf.wAttributes, ht * wt,
scrbuf.dwCursorPosition, addr(numwrote)) == 0: scrbuf.dwCursorPosition, addr(numwrote)) == 0:
OSError(OSLastError()) osError(osLastError())
else: else:
stdout.write("\e[2K") stdout.write("\e[2K")
setCursorXPos(0) setCursorXPos(0)
proc EraseScreen* = proc eraseScreen* =
## Erases the screen with the background colour and moves the cursor to home. ## Erases the screen with the background colour and moves the cursor to home.
when defined(windows): when defined(windows):
var scrbuf: TCONSOLE_SCREEN_BUFFER_INFO var scrbuf: TCONSOLESCREENBUFFERINFO
var numwrote: DWORD var numwrote: DWORD
var origin: TCoord # is inititalized to 0, 0 var origin: TCOORD # is inititalized to 0, 0
var hStdout = conHandle var hStdout = conHandle
if GetConsoleScreenBufferInfo(hStdout, addr(scrbuf)) == 0: OSError(OSLastError()) if GetConsoleScreenBufferInfo(hStdout, addr(scrbuf)) == 0: osError(osLastError())
if FillConsoleOutputCharacter(hStdout, ' ', scrbuf.dwSize.X*scrbuf.dwSize.Y, if FillConsoleOutputCharacter(hStdout, ' ', scrbuf.dwSize.X*scrbuf.dwSize.Y,
origin, addr(numwrote)) == 0: origin, addr(numwrote)) == 0:
OSError(OSLastError()) osError(osLastError())
if FillConsoleOutputAttribute(hStdout, scrbuf.wAttributes, if FillConsoleOutputAttribute(hStdout, scrbuf.wAttributes,
scrbuf.dwSize.X * scrbuf.dwSize.Y, scrbuf.dwSize.X * scrbuf.dwSize.Y,
origin, addr(numwrote)) == 0: origin, addr(numwrote)) == 0:
OSError(OSLastError()) osError(osLastError())
setCursorXPos(0) setCursorXPos(0)
else: else:
stdout.write("\e[2J") stdout.write("\e[2J")
proc ResetAttributes* {.noconv.} = proc resetAttributes* {.noconv.} =
## resets all attributes; it is advisable to register this as a quit proc ## resets all attributes; it is advisable to register this as a quit proc
## with ``system.addQuitProc(resetAttributes)``. ## with ``system.addQuitProc(resetAttributes)``.
when defined(windows): when defined(windows):
@ -227,7 +227,7 @@ proc setStyle*(style: set[TStyle]) =
for s in items(style): for s in items(style):
stdout.write("\e[" & $ord(s) & 'm') stdout.write("\e[" & $ord(s) & 'm')
proc WriteStyled*(txt: string, style: set[TStyle] = {styleBright}) = proc writeStyled*(txt: string, style: set[TStyle] = {styleBright}) =
## writes the text `txt` in a given `style`. ## writes the text `txt` in a given `style`.
when defined(windows): when defined(windows):
var old = getAttributes() var old = getAttributes()
@ -320,8 +320,8 @@ proc isatty*(f: TFile): bool =
proc styledEchoProcessArg(s: string) = write stdout, s proc styledEchoProcessArg(s: string) = write stdout, s
proc styledEchoProcessArg(style: TStyle) = setStyle({style}) proc styledEchoProcessArg(style: TStyle) = setStyle({style})
proc styledEchoProcessArg(style: set[TStyle]) = setStyle style proc styledEchoProcessArg(style: set[TStyle]) = setStyle style
proc styledEchoProcessArg(color: TForegroundColor) = setForeGroundColor color proc styledEchoProcessArg(color: TForegroundColor) = setForegroundColor color
proc styledEchoProcessArg(color: TBackgroundColor) = setBackGroundColor color proc styledEchoProcessArg(color: TBackgroundColor) = setBackgroundColor color
macro styledEcho*(m: varargs[expr]): stmt = macro styledEcho*(m: varargs[expr]): stmt =
## to be documented. ## to be documented.

View file

@ -732,10 +732,10 @@ proc contains*[T](s: TSlice[T], value: T): bool {.noSideEffect, inline.} =
result = s.a <= value and value <= s.b result = s.a <= value and value <= s.b
template `in` * (x, y: expr): expr {.immediate.} = contains(y, x) template `in` * (x, y: expr): expr {.immediate.} = contains(y, x)
template `not_in` * (x, y: expr): expr {.immediate.} = not contains(y, x) template `notin` * (x, y: expr): expr {.immediate.} = not contains(y, x)
proc `is` *[T, S](x: T, y: S): bool {.magic: "Is", noSideEffect.} proc `is` *[T, S](x: T, y: S): bool {.magic: "Is", noSideEffect.}
template `is_not` *(x, y: expr): expr {.immediate.} = not (x is y) template `isnot` *(x, y: expr): expr {.immediate.} = not (x is y)
proc `of` *[T, S](x: T, y: S): bool {.magic: "Of", noSideEffect.} proc `of` *[T, S](x: T, y: S): bool {.magic: "Of", noSideEffect.}

View file

@ -243,7 +243,7 @@ type
# remain compatible. # remain compatible.
type type
Textra*{.pure, final.} = object TExtra*{.pure, final.} = object
flags*: int ## Bits for which fields are set flags*: int ## Bits for which fields are set
study_data*: pointer ## Opaque data from pcre_study() study_data*: pointer ## Opaque data from pcre_study()
match_limit*: int ## Maximum number of calls to match() match_limit*: int ## Maximum number of calls to match()
@ -260,7 +260,7 @@ type
# without modification. # without modification.
type type
Tcallout_block*{.pure, final.} = object TCalloutBlock*{.pure, final.} = object
version*: cint ## Identifies version of block version*: cint ## Identifies version of block
callout_number*: cint ## Number compiled into pattern callout_number*: cint ## Number compiled into pattern
offset_vector*: ptr cint ## The offset vector offset_vector*: ptr cint ## The offset vector
@ -284,7 +284,7 @@ type
# User defined callback which provides a stack just before the match starts. # User defined callback which provides a stack just before the match starts.
type type
Tjit_callback* = proc(p: pointer): ptr Tjit_stack{.cdecl.} TJitCallback* = proc(p: pointer): ptr Tjit_stack{.cdecl.}
# Exported PCRE functions # Exported PCRE functions
@ -303,18 +303,18 @@ proc copy_substring*(a2: cstring, a3: ptr cint, a4: cint, a5: cint,
a6: cstring, a6: cstring,
a7: cint): cint{.cdecl, importc: "pcre_copy_substring", a7: cint): cint{.cdecl, importc: "pcre_copy_substring",
pcreImport.} pcreImport.}
proc dfa_exec*(a2: ptr TPcre, a3: ptr Textra, a4: cstring, a5: cint, proc dfa_exec*(a2: ptr TPcre, a3: ptr TExtra, a4: cstring, a5: cint,
a6: cint, a7: cint, a8: ptr cint, a9: cint, a10: ptr cint, a6: cint, a7: cint, a8: ptr cint, a9: cint, a10: ptr cint,
a11: cint): cint{.cdecl, importc: "pcre_dfa_exec", a11: cint): cint{.cdecl, importc: "pcre_dfa_exec",
pcreImport.} pcreImport.}
proc exec*(a2: ptr TPcre, a3: ptr Textra, a4: cstring, a5: cint, a6: cint, proc exec*(a2: ptr TPcre, a3: ptr TExtra, a4: cstring, a5: cint, a6: cint,
a7: cint, a8: ptr cint, a9: cint): cint {. a7: cint, a8: ptr cint, a9: cint): cint {.
cdecl, importc: "pcre_exec", pcreImport.} cdecl, importc: "pcre_exec", pcreImport.}
proc free_substring*(a2: cstring){.cdecl, importc: "pcre_free_substring", proc free_substring*(a2: cstring){.cdecl, importc: "pcre_free_substring",
pcreImport.} pcreImport.}
proc free_substring_list*(a2: cstringArray){.cdecl, proc free_substring_list*(a2: cstringArray){.cdecl,
importc: "pcre_free_substring_list", pcreImport.} importc: "pcre_free_substring_list", pcreImport.}
proc fullinfo*(a2: ptr TPcre, a3: ptr Textra, a4: cint, a5: pointer): cint{. proc fullinfo*(a2: ptr TPcre, a3: ptr TExtra, a4: cint, a5: pointer): cint{.
cdecl, importc: "pcre_fullinfo", pcreImport.} cdecl, importc: "pcre_fullinfo", pcreImport.}
proc get_named_substring*(a2: ptr TPcre, a3: cstring, a4: ptr cint, a5: cint, proc get_named_substring*(a2: ptr TPcre, a3: cstring, a4: ptr cint, a5: cint,
a6: cstring, a7: cstringArray): cint{.cdecl, a6: cstring, a7: cstringArray): cint{.cdecl,
@ -334,13 +334,13 @@ proc maketables*(): ptr char{.cdecl, importc: "pcre_maketables",
pcreImport.} pcreImport.}
proc refcount*(a2: ptr TPcre, a3: cint): cint{.cdecl, importc: "pcre_refcount", proc refcount*(a2: ptr TPcre, a3: cint): cint{.cdecl, importc: "pcre_refcount",
pcreImport.} pcreImport.}
proc study*(a2: ptr TPcre, a3: cint, a4: var cstring): ptr Textra{.cdecl, proc study*(a2: ptr TPcre, a3: cint, a4: var cstring): ptr TExtra{.cdecl,
importc: "pcre_study", pcreImport.} importc: "pcre_study", pcreImport.}
proc version*(): cstring{.cdecl, importc: "pcre_version", pcreImport.} proc version*(): cstring{.cdecl, importc: "pcre_version", pcreImport.}
# Utility functions for byte order swaps. # Utility functions for byte order swaps.
proc pattern_to_host_byte_order*(a2: ptr TPcre, a3: ptr Textra, proc pattern_to_host_byte_order*(a2: ptr TPcre, a3: ptr TExtra,
a4: ptr char): cint{.cdecl, importc: "pcre_pattern_to_host_byte_order", a4: ptr char): cint{.cdecl, importc: "pcre_pattern_to_host_byte_order",
pcreImport.} pcreImport.}
@ -350,7 +350,7 @@ proc jit_stack_alloc*(a2: cint, a3: cint): ptr Tjit_stack{.cdecl,
importc: "pcre_jit_stack_alloc", pcreImport.} importc: "pcre_jit_stack_alloc", pcreImport.}
proc jit_stack_free*(a2: ptr Tjit_stack){.cdecl, importc: "pcre_jit_stack_free", proc jit_stack_free*(a2: ptr Tjit_stack){.cdecl, importc: "pcre_jit_stack_free",
pcreImport.} pcreImport.}
proc assign_jit_stack*(a2: ptr Textra, a3: Tjit_callback, a4: pointer){.cdecl, proc assign_jit_stack*(a2: ptr TExtra, a3: TJitCallback, a4: pointer){.cdecl,
importc: "pcre_assign_jit_stack", pcreImport.} importc: "pcre_assign_jit_stack", pcreImport.}
var var

View file

@ -56,7 +56,7 @@ var
proc ask(msg: string): string = proc ask(msg: string): string =
stdout.write(msg) stdout.write(msg)
result = stdin.readline() result = stdin.readLine()
proc Confirm: TConfirmEnum = proc Confirm: TConfirmEnum =
while true: while true:
@ -66,7 +66,7 @@ proc Confirm: TConfirmEnum =
of "l", "all": return ceAll of "l", "all": return ceAll
of "n", "no": return ceNo of "n", "no": return ceNo
of "e", "none": return ceNone of "e", "none": return ceNone
else: nil else: discard
proc countLines(s: string, first, last: int): int = proc countLines(s: string, first, last: int): int =
var i = first var i = first
@ -308,7 +308,7 @@ checkOptions({optIgnoreCase, optIgnoreStyle}, "ignore_case", "ignore_style")
if optStdin in options: if optStdin in options:
pattern = ask("pattern [ENTER to exit]: ") pattern = ask("pattern [ENTER to exit]: ")
if IsNil(pattern) or pattern.len == 0: quit(0) if isNil(pattern) or pattern.len == 0: quit(0)
if optReplace in options: if optReplace in options:
replacement = ask("replacement [supports $1, $# notations]: ") replacement = ask("replacement [supports $1, $# notations]: ")