lib/pure/p-t - Dropped 'T' from types

This commit is contained in:
pdw 2015-05-24 22:34:41 -05:00 • committed by Araq
commit d18e18060e
13 changed files with 89 additions and 84 deletions

View file

@ -133,7 +133,7 @@ proc cmdLineRest*(p: OptParser): TaintedString {.rtl, extern: "npo$1".} =
when declared(initOptParser): when declared(initOptParser):
iterator getopt*(): tuple[kind: CmdLineKind, key, val: TaintedString] = iterator getopt*(): tuple[kind: CmdLineKind, key, val: TaintedString] =
## This is an convenience iterator for iterating over the command line. ## This is an convenience iterator for iterating over the command line.
## This uses the TOptParser object. Example: ## This uses the OptParser object. Example:
## ##
## .. code-block:: nim ## .. code-block:: nim
## var ## var

View file

@ -74,8 +74,8 @@ type
line: int ## line the symbol has been declared/used in line: int ## line the symbol has been declared/used in
col: int ## column the symbol has been declared/used in col: int ## column the symbol has been declared/used in
flags: set[NonTerminalFlag] ## the nonterminal's flags flags: set[NonTerminalFlag] ## the nonterminal's flags
rule: TNode ## the rule that the symbol refers to rule: Node ## the rule that the symbol refers to
TNode {.shallow.} = object Node {.shallow.} = object
case kind: PegKind case kind: PegKind
of pkEmpty..pkWhitespace: nil of pkEmpty..pkWhitespace: nil
of pkTerminal, pkTerminalIgnoreCase, pkTerminalIgnoreStyle: term: string of pkTerminal, pkTerminalIgnoreCase, pkTerminalIgnoreStyle: term: string
@ -83,12 +83,12 @@ type
of pkCharChoice, pkGreedyRepSet: charChoice: ref set[char] of pkCharChoice, pkGreedyRepSet: charChoice: ref set[char]
of pkNonTerminal: nt: NonTerminal of pkNonTerminal: nt: NonTerminal
of pkBackRef..pkBackRefIgnoreStyle: index: range[0..MaxSubpatterns] of pkBackRef..pkBackRefIgnoreStyle: index: range[0..MaxSubpatterns]
else: sons: seq[TNode] else: sons: seq[Node]
NonTerminal* = ref NonTerminalObj NonTerminal* = ref NonTerminalObj
Peg* = TNode ## type that represents a PEG Peg* = Node ## type that represents a PEG
{.deprecated: [TPeg: Peg].} {.deprecated: [TPeg: Peg, TNode: Node].}
proc term*(t: string): Peg {.nosideEffect, rtl, extern: "npegs$1Str".} = proc term*(t: string): Peg {.nosideEffect, rtl, extern: "npegs$1Str".} =
## constructs a PEG from a terminal string ## constructs a PEG from a terminal string
@ -1014,12 +1014,12 @@ proc split*(s: string, sep: Peg): seq[string] {.
# ------------------- scanner ------------------------------------------------- # ------------------- scanner -------------------------------------------------
type type
TModifier = enum Modifier = enum
modNone, modNone,
modVerbatim, modVerbatim,
modIgnoreCase, modIgnoreCase,
modIgnoreStyle modIgnoreStyle
TTokKind = enum ## enumeration of all tokens TokKind = enum ## enumeration of all tokens
tkInvalid, ## invalid token tkInvalid, ## invalid token
tkEof, ## end of file reached tkEof, ## end of file reached
tkAny, ## . tkAny, ## .
@ -1046,9 +1046,9 @@ type
tkDollar, ## '$' tkDollar, ## '$'
tkHat ## '^' tkHat ## '^'
TToken {.final.} = object ## a token Token {.final.} = object ## a token
kind: TTokKind ## the type of the token kind: TokKind ## the type of the token
modifier: TModifier modifier: Modifier
literal: string ## the parsed (string) literal literal: string ## the parsed (string) literal
charset: set[char] ## if kind == tkCharSet charset: set[char] ## if kind == tkCharSet
index: int ## if kind == tkBackref index: int ## if kind == tkBackref
@ -1060,9 +1060,10 @@ type
lineStart: int ## index of last line start in buffer lineStart: int ## index of last line start in buffer
colOffset: int ## column to add colOffset: int ## column to add
filename: string filename: string
{.deprecated: [TTokKind: TokKind, TToken: Token, TModifier: Modifier].}
const const
tokKindToStr: array[TTokKind, string] = [ tokKindToStr: array[TokKind, string] = [
"invalid", "[EOF]", ".", "_", "identifier", "string literal", "invalid", "[EOF]", ".", "_", "identifier", "string literal",
"character set", "(", ")", "{", "}", "{@}", "character set", "(", ")", "{", "}", "{@}",
"<-", "/", "*", "+", "&", "!", "?", "<-", "/", "*", "+", "&", "!", "?",
@ -1114,7 +1115,7 @@ proc handleHexChar(c: var PegLexer, xi: var int) =
inc(c.bufpos) inc(c.bufpos)
else: discard else: discard
proc getEscapedChar(c: var PegLexer, tok: var TToken) = proc getEscapedChar(c: var PegLexer, tok: var Token) =
inc(c.bufpos) inc(c.bufpos)
case c.buf[c.bufpos] case c.buf[c.bufpos]
of 'r', 'R', 'c', 'C': of 'r', 'R', 'c', 'C':
@ -1185,7 +1186,7 @@ proc skip(c: var PegLexer) =
break # EndOfFile also leaves the loop break # EndOfFile also leaves the loop
c.bufpos = pos c.bufpos = pos
proc getString(c: var PegLexer, tok: var TToken) = proc getString(c: var PegLexer, tok: var Token) =
tok.kind = tkStringLit tok.kind = tkStringLit
var pos = c.bufpos + 1 var pos = c.bufpos + 1
var buf = c.buf var buf = c.buf
@ -1207,7 +1208,7 @@ proc getString(c: var PegLexer, tok: var TToken) =
inc(pos) inc(pos)
c.bufpos = pos c.bufpos = pos
proc getDollar(c: var PegLexer, tok: var TToken) = proc getDollar(c: var PegLexer, tok: var Token) =
var pos = c.bufpos + 1 var pos = c.bufpos + 1
var buf = c.buf var buf = c.buf
if buf[pos] in {'0'..'9'}: if buf[pos] in {'0'..'9'}:
@ -1220,7 +1221,7 @@ proc getDollar(c: var PegLexer, tok: var TToken) =
tok.kind = tkDollar tok.kind = tkDollar
c.bufpos = pos c.bufpos = pos
proc getCharSet(c: var PegLexer, tok: var TToken) = proc getCharSet(c: var PegLexer, tok: var Token) =
tok.kind = tkCharSet tok.kind = tkCharSet
tok.charset = {} tok.charset = {}
var pos = c.bufpos + 1 var pos = c.bufpos + 1
@ -1271,7 +1272,7 @@ proc getCharSet(c: var PegLexer, tok: var TToken) =
c.bufpos = pos c.bufpos = pos
if caret: tok.charset = {'\1'..'\xFF'} - tok.charset if caret: tok.charset = {'\1'..'\xFF'} - tok.charset
proc getSymbol(c: var PegLexer, tok: var TToken) = proc getSymbol(c: var PegLexer, tok: var Token) =
var pos = c.bufpos var pos = c.bufpos
var buf = c.buf var buf = c.buf
while true: while true:
@ -1281,7 +1282,7 @@ proc getSymbol(c: var PegLexer, tok: var TToken) =
c.bufpos = pos c.bufpos = pos
tok.kind = tkIdentifier tok.kind = tkIdentifier
proc getBuiltin(c: var PegLexer, tok: var TToken) = proc getBuiltin(c: var PegLexer, tok: var Token) =
if c.buf[c.bufpos+1] in strutils.Letters: if c.buf[c.bufpos+1] in strutils.Letters:
inc(c.bufpos) inc(c.bufpos)
getSymbol(c, tok) getSymbol(c, tok)
@ -1290,7 +1291,7 @@ proc getBuiltin(c: var PegLexer, tok: var TToken) =
tok.kind = tkEscaped tok.kind = tkEscaped
getEscapedChar(c, tok) # may set tok.kind to tkInvalid getEscapedChar(c, tok) # may set tok.kind to tkInvalid
proc getTok(c: var PegLexer, tok: var TToken) = proc getTok(c: var PegLexer, tok: var Token) =
tok.kind = tkInvalid tok.kind = tkInvalid
tok.modifier = modNone tok.modifier = modNone
setLen(tok.literal, 0) setLen(tok.literal, 0)
@ -1408,9 +1409,9 @@ type
EInvalidPeg* = object of ValueError ## raised if an invalid EInvalidPeg* = object of ValueError ## raised if an invalid
## PEG has been detected ## PEG has been detected
PegParser = object of PegLexer ## the PEG parser object PegParser = object of PegLexer ## the PEG parser object
tok: TToken tok: Token
nonterms: seq[NonTerminal] nonterms: seq[NonTerminal]
modifier: TModifier modifier: Modifier
captures: int captures: int
identIsVerbatim: bool identIsVerbatim: bool
skip: Peg skip: Peg
@ -1425,7 +1426,7 @@ proc getTok(p: var PegParser) =
getTok(p, p.tok) getTok(p, p.tok)
if p.tok.kind == tkInvalid: pegError(p, "invalid token") if p.tok.kind == tkInvalid: pegError(p, "invalid token")
proc eat(p: var PegParser, kind: TTokKind) = proc eat(p: var PegParser, kind: TokKind) =
if p.tok.kind == kind: getTok(p) if p.tok.kind == kind: getTok(p)
else: pegError(p, tokKindToStr[kind] & " expected") else: pegError(p, tokKindToStr[kind] & " expected")
@ -1439,13 +1440,13 @@ proc getNonTerminal(p: var PegParser, name: string): NonTerminal =
result = newNonTerminal(name, getLine(p), getColumn(p)) result = newNonTerminal(name, getLine(p), getColumn(p))
add(p.nonterms, result) add(p.nonterms, result)
proc modifiedTerm(s: string, m: TModifier): Peg = proc modifiedTerm(s: string, m: Modifier): Peg =
case m case m
of modNone, modVerbatim: result = term(s) of modNone, modVerbatim: result = term(s)
of modIgnoreCase: result = termIgnoreCase(s) of modIgnoreCase: result = termIgnoreCase(s)
of modIgnoreStyle: result = termIgnoreStyle(s) of modIgnoreStyle: result = termIgnoreStyle(s)
proc modifiedBackref(s: int, m: TModifier): Peg = proc modifiedBackref(s: int, m: Modifier): Peg =
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)

View file

@ -206,13 +206,13 @@ proc abs*[T](x: Rational[T]): Rational[T] =
result.num = abs x.num result.num = abs x.num
result.den = abs x.den result.den = abs x.den
proc hash*[T](x: Rational[T]): THash = proc hash*[T](x: Rational[T]): Hash =
## Computes hash for rational `x` ## Computes hash for rational `x`
# reduce first so that hash(x) == hash(y) for x == y # reduce first so that hash(x) == hash(y) for x == y
var copy = x var copy = x
reduce(copy) reduce(copy)
var h: THash = 0 var h: Hash = 0
h = h !& hash(copy.num) h = h !& hash(copy.num)
h = h !& hash(copy.den) h = h !& hash(copy.den)
result = !$h result = !$h

View file

@ -106,13 +106,13 @@ proc `$`*(p: Port): string {.borrow.}
## returns the port number as a string ## returns the port number as a string
proc toInt*(domain: Domain): cint proc toInt*(domain: Domain): cint
## Converts the TDomain enum to a platform-dependent ``cint``. ## Converts the Domain enum to a platform-dependent ``cint``.
proc toInt*(typ: SockType): cint proc toInt*(typ: SockType): cint
## Converts the TType enum to a platform-dependent ``cint``. ## Converts the SockType enum to a platform-dependent ``cint``.
proc toInt*(p: Protocol): cint proc toInt*(p: Protocol): cint
## Converts the TProtocol enum to a platform-dependent ``cint``. ## Converts the Protocol enum to a platform-dependent ``cint``.
when not useWinVersion: when not useWinVersion:
proc toInt(domain: Domain): cint = proc toInt(domain: Domain): cint =

View file

@ -10,8 +10,8 @@
## This module implements a redis client. It allows you to connect to a ## This module implements a redis client. It allows you to connect to a
## redis-server instance, send commands and receive replies. ## redis-server instance, send commands and receive replies.
## ##
## **Beware**: Most (if not all) functions that return a ``TRedisString`` may ## **Beware**: Most (if not all) functions that return a ``RedisString`` may
## return ``redisNil``, and functions which return a ``TRedisList`` ## return ``redisNil``, and functions which return a ``RedisList``
## may return ``nil``. ## may return ``nil``.
import sockets, os, strutils, parseutils import sockets, os, strutils, parseutils
@ -843,27 +843,27 @@ proc pfmerge*(r: Redis, destination: string, sources: varargs[string]) =
# TODO: pub/sub -- I don't think this will work synchronously. # TODO: pub/sub -- I don't think this will work synchronously.
discard """ discard """
proc psubscribe*(r: TRedis, pattern: openarray[string]): ???? = proc psubscribe*(r: Redis, pattern: openarray[string]): ???? =
## Listen for messages published to channels matching the given patterns ## Listen for messages published to channels matching the given patterns
r.socket.send("PSUBSCRIBE $#\c\L" % pattern) r.socket.send("PSUBSCRIBE $#\c\L" % pattern)
return ??? return ???
proc publish*(r: TRedis, channel: string, message: string): TRedisInteger = proc publish*(r: Redis, channel: string, message: string): RedisInteger =
## Post a message to a channel ## Post a message to a channel
r.socket.send("PUBLISH $# $#\c\L" % [channel, message]) r.socket.send("PUBLISH $# $#\c\L" % [channel, message])
return r.readInteger() return r.readInteger()
proc punsubscribe*(r: TRedis, [pattern: openarray[string], : string): ???? = proc punsubscribe*(r: Redis, [pattern: openarray[string], : string): ???? =
## Stop listening for messages posted to channels matching the given patterns ## Stop listening for messages posted to channels matching the given patterns
r.socket.send("PUNSUBSCRIBE $# $#\c\L" % [[pattern.join(), ]) r.socket.send("PUNSUBSCRIBE $# $#\c\L" % [[pattern.join(), ])
return ??? return ???
proc subscribe*(r: TRedis, channel: openarray[string]): ???? = proc subscribe*(r: Redis, channel: openarray[string]): ???? =
## Listen for messages published to the given channels ## Listen for messages published to the given channels
r.socket.send("SUBSCRIBE $#\c\L" % channel.join) r.socket.send("SUBSCRIBE $#\c\L" % channel.join)
return ??? return ???
proc unsubscribe*(r: TRedis, [channel: openarray[string], : string): ???? = proc unsubscribe*(r: Redis, [channel: openarray[string], : string): ???? =
## Stop listening for messages posted to the given channels ## Stop listening for messages posted to the given channels
r.socket.send("UNSUBSCRIBE $# $#\c\L" % [[channel.join(), ]) r.socket.send("UNSUBSCRIBE $# $#\c\L" % [[channel.join(), ])
return ??? return ???
@ -991,7 +991,7 @@ proc lastsave*(r: Redis): RedisInteger =
return r.readInteger() return r.readInteger()
discard """ discard """
proc monitor*(r: TRedis) = proc monitor*(r: Redis) =
## Listen for all requests received by the server in real time ## Listen for all requests received by the server in real time
r.socket.send("MONITOR\c\L") r.socket.send("MONITOR\c\L")
raiseNoOK(r.readStatus(), r.pipeline.enabled) raiseNoOK(r.readStatus(), r.pipeline.enabled)

View file

@ -18,7 +18,7 @@ elif defined(windows):
else: else:
import posix import posix
proc hash*(x: SocketHandle): THash {.borrow.} proc hash*(x: SocketHandle): Hash {.borrow.}
proc `$`*(x: SocketHandle): string {.borrow.} proc `$`*(x: SocketHandle): string {.borrow.}
type type
@ -41,7 +41,7 @@ when defined(nimdoc):
proc register*(s: Selector, fd: SocketHandle, events: set[Event], proc register*(s: Selector, fd: SocketHandle, events: set[Event],
data: RootRef): SelectorKey {.discardable.} = data: RootRef): SelectorKey {.discardable.} =
## Registers file descriptor ``fd`` to selector ``s`` with a set of TEvent ## Registers file descriptor ``fd`` to selector ``s`` with a set of Event
## ``events``. ## ``events``.
proc update*(s: Selector, fd: SocketHandle, proc update*(s: Selector, fd: SocketHandle,

View file

@ -23,7 +23,7 @@ type
sexpListStart, ## start of a list: the ``(`` token sexpListStart, ## start of a list: the ``(`` token
sexpListEnd, ## end of a list: the ``)`` token sexpListEnd, ## end of a list: the ``)`` token
TTokKind = enum # must be synchronized with SexpEventKind! TokKind = enum # must be synchronized with SexpEventKind!
tkError, tkError,
tkEof, tkEof,
tkString, tkString,
@ -45,9 +45,10 @@ type
SexpParser* = object of BaseLexer ## the parser object. SexpParser* = object of BaseLexer ## the parser object.
a: string a: string
tok: TTokKind tok: TokKind
kind: SexpEventKind kind: SexpEventKind
err: SexpError err: SexpError
{.deprecated: [TTokKind: TokKind].}
const const
errorMessages: array [SexpError, string] = [ errorMessages: array [SexpError, string] = [
@ -57,7 +58,7 @@ const
"'\"' or \"'\" expected", "'\"' or \"'\" expected",
"EOF expected", "EOF expected",
] ]
tokToStr: array [TTokKind, string] = [ tokToStr: array [TokKind, string] = [
"invalid token", "invalid token",
"EOF", "EOF",
"string literal", "string literal",
@ -119,7 +120,7 @@ proc handleHexChar(c: char, x: var int): bool =
of 'A'..'F': x = (x shl 4) or (ord(c) - ord('A') + 10) of 'A'..'F': x = (x shl 4) or (ord(c) - ord('A') + 10)
else: result = false # error else: result = false # error
proc parseString(my: var SexpParser): TTokKind = proc parseString(my: var SexpParser): TokKind =
result = tkString result = tkString
var pos = my.bufpos + 1 var pos = my.bufpos + 1
var buf = my.buf var buf = my.buf
@ -217,7 +218,7 @@ proc parseSymbol(my: var SexpParser) =
inc(pos) inc(pos)
my.bufpos = pos my.bufpos = pos
proc getTok(my: var SexpParser): TTokKind = proc getTok(my: var SexpParser): TokKind =
setLen(my.a, 0) setLen(my.a, 0)
case my.buf[my.bufpos] case my.buf[my.bufpos]
of '-', '0'..'9': # numbers that start with a . are not parsed of '-', '0'..'9': # numbers that start with a . are not parsed
@ -466,7 +467,7 @@ proc `==`* (a,b: SexpNode): bool =
of SCons: of SCons:
a.car == b.car and a.cdr == b.cdr a.car == b.car and a.cdr == b.cdr
proc hash* (n:SexpNode): THash = proc hash* (n:SexpNode): Hash =
## Compute the hash for a SEXP node ## Compute the hash for a SEXP node
case n.kind case n.kind
of SList: of SList:
@ -620,7 +621,7 @@ iterator mitems*(node: var SexpNode): var SexpNode =
for i in mitems(node.elems): for i in mitems(node.elems):
yield i yield i
proc eat(p: var SexpParser, tok: TTokKind) = proc eat(p: var SexpParser, tok: TokKind) =
if p.tok == tok: discard getTok(p) if p.tok == tok: discard getTok(p)
else: raiseParseErr(p, tokToStr[tok]) else: raiseParseErr(p, tokToStr[tok])

View file

@ -75,7 +75,7 @@ const
BufferSize*: int = 4000 ## size of a buffered socket's buffer BufferSize*: int = 4000 ## size of a buffered socket's buffer
type type
TSocketImpl = object ## socket type SocketImpl = object ## socket type
fd: SocketHandle fd: SocketHandle
case isBuffered: bool # determines whether this socket is buffered. case isBuffered: bool # determines whether this socket is buffered.
of true: of true:
@ -94,7 +94,7 @@ type
of false: nil of false: nil
nonblocking: bool nonblocking: bool
Socket* = ref TSocketImpl Socket* = ref SocketImpl
Port* = distinct uint16 ## port type Port* = distinct uint16 ## port type
@ -146,8 +146,9 @@ type
{.deprecated: [TSocket: Socket, TType: SockType, TPort: Port, TDomain: Domain, {.deprecated: [TSocket: Socket, TType: SockType, TPort: Port, TDomain: Domain,
TProtocol: Protocol, TServent: Servent, THostent: Hostent, TProtocol: Protocol, TServent: Servent, THostent: Hostent,
TSOBool: SOBool, TRecvLineResult: RecvLineResult, TSOBool: SOBool, TRecvLineResult: RecvLineResult,
TReadLineResult: ReadLineResult, ETimeout: TimeoutError].} TReadLineResult: ReadLineResult, ETimeout: TimeoutError,
TSocketImpl: SocketImpl].}
when defined(booting): when defined(booting):
let invalidSocket*: Socket = nil ## invalid socket let invalidSocket*: Socket = nil ## invalid socket

View file

@ -327,7 +327,7 @@ proc newStringStream*(s: string = ""): StringStream =
when not defined(js): when not defined(js):
type type
FileStream* = ref FileStreamObj ## a stream that encapsulates a `TFile` FileStream* = ref FileStreamObj ## a stream that encapsulates a `File`
FileStreamObj* = object of Stream FileStreamObj* = object of Stream
f: File f: File
{.deprecated: [PFileStream: FileStream, TFileStream: FileStreamObj].} {.deprecated: [PFileStream: FileStream, TFileStream: FileStreamObj].}

View file

@ -74,7 +74,7 @@ const
growthFactor = 2 growthFactor = 2
startSize = 64 startSize = 64
proc myhash(t: StringTableRef, key: string): THash = proc myhash(t: StringTableRef, key: string): Hash =
case t.mode case t.mode
of modeCaseSensitive: result = hashes.hash(key) of modeCaseSensitive: result = hashes.hash(key)
of modeCaseInsensitive: result = hashes.hashIgnoreCase(key) of modeCaseInsensitive: result = hashes.hashIgnoreCase(key)
@ -90,11 +90,11 @@ proc mustRehash(length, counter: int): bool =
assert(length > counter) assert(length > counter)
result = (length * 2 < counter * 3) or (length - counter < 4) result = (length * 2 < counter * 3) or (length - counter < 4)
proc nextTry(h, maxHash: THash): THash {.inline.} = proc nextTry(h, maxHash: Hash): Hash {.inline.} =
result = ((5 * h) + 1) and maxHash result = ((5 * h) + 1) and maxHash
proc rawGet(t: StringTableRef, key: string): int = proc rawGet(t: StringTableRef, key: string): int =
var h: THash = myhash(t, key) and high(t.data) # start with real hash value var h: Hash = myhash(t, key) and high(t.data) # start with real hash value
while not isNil(t.data[h].key): 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 return h
@ -122,7 +122,7 @@ proc hasKey*(t: StringTableRef, key: string): bool {.rtl, extern: "nst$1".} =
result = rawGet(t, key) >= 0 result = rawGet(t, key) >= 0
proc rawInsert(t: StringTableRef, data: var KeyValuePairSeq, key, val: string) = proc rawInsert(t: StringTableRef, data: var KeyValuePairSeq, key, val: string) =
var h: THash = myhash(t, key) and high(data) var h: Hash = myhash(t, key) and high(data)
while not isNil(data[h].key): while not isNil(data[h].key):
h = nextTry(h, high(data)) h = nextTry(h, high(data))
data[h].key = key data[h].key = key

View file

@ -23,7 +23,8 @@ import parseutils
include "system/inclrtl" include "system/inclrtl"
type type
TCharSet* {.deprecated.} = set[char] # for compatibility with Nim CharSet* {.deprecated.} = set[char] # for compatibility with Nim
{.deprecated: [TCharSet: CharSet].}
const const
Whitespace* = {' ', '\t', '\v', '\r', '\l', '\f'} Whitespace* = {' ', '\t', '\v', '\r', '\l', '\f'}

View file

@ -37,13 +37,14 @@ proc raiseInvalidFormat(msg: string) {.noinline.} =
raise newException(SubexError, "invalid format string: " & msg) raise newException(SubexError, "invalid format string: " & msg)
type type
TFormatParser = object {.pure, final.} FormatParser = object {.pure, final.}
when defined(js): when defined(js):
f: string # we rely on the '\0' terminator f: string # we rely on the '\0' terminator
# which JS's native string doesn't have # which JS's native string doesn't have
else: else:
f: cstring f: cstring
num, i, lineLen: int num, i, lineLen: int
{.deprecated: [TFormatParser: FormatParser].}
template call(x: stmt) {.immediate.} = template call(x: stmt) {.immediate.} =
p.i = i p.i = i
@ -57,7 +58,7 @@ template callNoLineLenTracking(x: stmt) {.immediate.} =
i = p.i i = p.i
p.lineLen = oldLineLen p.lineLen = oldLineLen
proc getFormatArg(p: var TFormatParser, a: openArray[string]): int = proc getFormatArg(p: var FormatParser, a: openArray[string]): int =
const PatternChars = {'a'..'z', 'A'..'Z', '0'..'9', '\128'..'\255', '_'} const PatternChars = {'a'..'z', 'A'..'Z', '0'..'9', '\128'..'\255', '_'}
var i = p.i var i = p.i
var f = p.f var f = p.f
@ -90,22 +91,22 @@ proc getFormatArg(p: var TFormatParser, a: openArray[string]): int =
if result >=% a.len: raiseInvalidFormat("index out of bounds: " & $result) if result >=% a.len: raiseInvalidFormat("index out of bounds: " & $result)
p.i = i p.i = i
proc scanDollar(p: var TFormatParser, a: openarray[string], s: var string) {. proc scanDollar(p: var FormatParser, a: openarray[string], s: var string) {.
noSideEffect.} noSideEffect.}
proc emitChar(p: var TFormatParser, x: var string, ch: char) {.inline.} = proc emitChar(p: var FormatParser, x: var string, ch: char) {.inline.} =
x.add(ch) x.add(ch)
if ch == '\L': p.lineLen = 0 if ch == '\L': p.lineLen = 0
else: inc p.lineLen else: inc p.lineLen
proc emitStrLinear(p: var TFormatParser, x: var string, y: string) {.inline.} = proc emitStrLinear(p: var FormatParser, x: var string, y: string) {.inline.} =
for ch in items(y): emitChar(p, x, ch) for ch in items(y): emitChar(p, x, ch)
proc emitStr(p: var TFormatParser, x: var string, y: string) {.inline.} = proc emitStr(p: var FormatParser, x: var string, y: string) {.inline.} =
x.add(y) x.add(y)
inc p.lineLen, y.len inc p.lineLen, y.len
proc scanQuote(p: var TFormatParser, x: var string, toAdd: bool) = proc scanQuote(p: var FormatParser, x: var string, toAdd: bool) =
var i = p.i+1 var i = p.i+1
var f = p.f var f = p.f
while true: while true:
@ -120,7 +121,7 @@ proc scanQuote(p: var TFormatParser, x: var string, toAdd: bool) =
inc i inc i
p.i = i p.i = i
proc scanBranch(p: var TFormatParser, a: openArray[string], proc scanBranch(p: var FormatParser, a: openArray[string],
x: var string, choice: int) = x: var string, choice: int) =
var i = p.i var i = p.i
var f = p.f var f = p.f
@ -167,7 +168,7 @@ proc scanBranch(p: var TFormatParser, a: openArray[string],
i = last i = last
p.i = i+1 p.i = i+1
proc scanSlice(p: var TFormatParser, a: openarray[string]): tuple[x, y: int] = proc scanSlice(p: var FormatParser, a: openarray[string]): tuple[x, y: int] =
var slice = false var slice = false
var i = p.i var i = p.i
var f = p.f var f = p.f
@ -193,7 +194,7 @@ proc scanSlice(p: var TFormatParser, a: openarray[string]): tuple[x, y: int] =
inc i inc i
p.i = i p.i = i
proc scanDollar(p: var TFormatParser, a: openarray[string], s: var string) = proc scanDollar(p: var FormatParser, a: openarray[string], s: var string) =
var i = p.i var i = p.i
var f = p.f var f = p.f
case f[i] case f[i]
@ -312,7 +313,7 @@ proc subex*(s: string): Subex =
proc addf*(s: var string, formatstr: Subex, a: varargs[string, `$`]) {. proc addf*(s: var string, formatstr: Subex, a: varargs[string, `$`]) {.
noSideEffect, rtl, extern: "nfrmtAddf".} = noSideEffect, rtl, extern: "nfrmtAddf".} =
## The same as ``add(s, formatstr % a)``, but more efficient. ## The same as ``add(s, formatstr % a)``, but more efficient.
var p: TFormatParser var p: FormatParser
p.f = formatstr.string p.f = formatstr.string
var i = 0 var i = 0
while i < len(formatstr.string): while i < len(formatstr.string):
@ -386,10 +387,10 @@ when isMainModule:
longishA, longishA,
longish)""" longish)"""
assert "type TMyEnum* = enum\n $', '2i'\n '{..}" % ["fieldA", assert "type MyEnum* = enum\n $', '2i'\n '{..}" % ["fieldA",
"fieldB", "FiledClkad", "fieldD", "fieldE", "longishFieldName"] == "fieldB", "FiledClkad", "fieldD", "fieldE", "longishFieldName"] ==
strutils.unindent """ strutils.unindent """
type TMyEnum* = enum type MyEnum* = enum
fieldA, fieldB, fieldA, fieldB,
FiledClkad, fieldD, FiledClkad, fieldD,
fieldE, longishFieldName""" fieldE, longishFieldName"""
@ -400,11 +401,11 @@ when isMainModule:
doAssert subex"$['''|'|''''|']']#" % "0" == "'|" doAssert subex"$['''|'|''''|']']#" % "0" == "'|"
assert subex("type\n TEnum = enum\n $', '40c'\n '{..}") % [ assert subex("type\n Enum = enum\n $', '40c'\n '{..}") % [
"fieldNameA", "fieldNameB", "fieldNameC", "fieldNameD"] == "fieldNameA", "fieldNameB", "fieldNameC", "fieldNameD"] ==
strutils.unindent """ strutils.unindent """
type type
TEnum = enum Enum = enum
fieldNameA, fieldNameB, fieldNameC, fieldNameA, fieldNameB, fieldNameC,
fieldNameD""" fieldNameD"""

View file

@ -20,7 +20,7 @@ when defined(windows):
import windows, os import windows, os
var var
conHandle: THandle conHandle: Handle
# = createFile("CONOUT$", GENERIC_WRITE, 0, nil, OPEN_ALWAYS, 0, 0) # = createFile("CONOUT$", GENERIC_WRITE, 0, nil, OPEN_ALWAYS, 0, 0)
block: block:
@ -30,13 +30,13 @@ when defined(windows):
raiseOSError(osLastError()) raiseOSError(osLastError())
proc getCursorPos(): tuple [x,y: int] = proc getCursorPos(): tuple [x,y: int] =
var c: TCONSOLESCREENBUFFERINFO var c: CONSOLESCREENBUFFERINFO
if GetConsoleScreenBufferInfo(conHandle, addr(c)) == 0: if GetConsoleScreenBufferInfo(conHandle, addr(c)) == 0:
raiseOSError(osLastError()) raiseOSError(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: TCONSOLESCREENBUFFERINFO var c: CONSOLESCREENBUFFERINFO
# 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
@ -51,11 +51,11 @@ else:
proc setRaw(fd: FileHandle, time: cint = TCSAFLUSH) = proc setRaw(fd: FileHandle, time: cint = TCSAFLUSH) =
var mode: Termios var mode: Termios
discard fd.tcgetattr(addr mode) discard fd.tcgetattr(addr mode)
mode.c_iflag = mode.c_iflag and not Tcflag(BRKINT or ICRNL or INPCK or mode.c_iflag = mode.c_iflag and not Cflag(BRKINT or ICRNL or INPCK or
ISTRIP or IXON) ISTRIP or IXON)
mode.c_oflag = mode.c_oflag and not Tcflag(OPOST) mode.c_oflag = mode.c_oflag and not Cflag(OPOST)
mode.c_cflag = (mode.c_cflag and not Tcflag(CSIZE or PARENB)) or CS8 mode.c_cflag = (mode.c_cflag and not Cflag(CSIZE or PARENB)) or CS8
mode.c_lflag = mode.c_lflag and not Tcflag(ECHO or ICANON or IEXTEN or ISIG) mode.c_lflag = mode.c_lflag and not Cflag(ECHO or ICANON or IEXTEN or ISIG)
mode.c_cc[VMIN] = 1.cuchar mode.c_cc[VMIN] = 1.cuchar
mode.c_cc[VTIME] = 0.cuchar mode.c_cc[VTIME] = 0.cuchar
discard fd.tcsetattr(time, addr mode) discard fd.tcsetattr(time, addr mode)
@ -64,7 +64,7 @@ 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: COORD
c.X = int16(x) c.X = int16(x)
c.Y = int16(y) c.Y = int16(y)
if SetConsoleCursorPosition(conHandle, c) == 0: raiseOSError(osLastError()) if SetConsoleCursorPosition(conHandle, c) == 0: raiseOSError(osLastError())
@ -75,7 +75,7 @@ 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: TCONSOLESCREENBUFFERINFO var scrbuf: CONSOLESCREENBUFFERINFO
var hStdout = conHandle var hStdout = conHandle
if GetConsoleScreenBufferInfo(hStdout, addr(scrbuf)) == 0: if GetConsoleScreenBufferInfo(hStdout, addr(scrbuf)) == 0:
raiseOSError(osLastError()) raiseOSError(osLastError())
@ -91,7 +91,7 @@ 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: TCONSOLESCREENBUFFERINFO var scrbuf: CONSOLESCREENBUFFERINFO
var hStdout = conHandle var hStdout = conHandle
if GetConsoleScreenBufferInfo(hStdout, addr(scrbuf)) == 0: if GetConsoleScreenBufferInfo(hStdout, addr(scrbuf)) == 0:
raiseOSError(osLastError()) raiseOSError(osLastError())
@ -172,7 +172,7 @@ else:
proc eraseLine* = proc eraseLine* =
## Erases the entire current line. ## Erases the entire current line.
when defined(windows): when defined(windows):
var scrbuf: TCONSOLESCREENBUFFERINFO var scrbuf: CONSOLESCREENBUFFERINFO
var numwrote: DWORD var numwrote: DWORD
var hStdout = conHandle var hStdout = conHandle
if GetConsoleScreenBufferInfo(hStdout, addr(scrbuf)) == 0: if GetConsoleScreenBufferInfo(hStdout, addr(scrbuf)) == 0:
@ -196,9 +196,9 @@ proc eraseLine* =
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: TCONSOLESCREENBUFFERINFO var scrbuf: CONSOLESCREENBUFFERINFO
var numwrote: DWORD var numwrote: DWORD
var origin: TCOORD # is inititalized to 0, 0 var origin: COORD # is inititalized to 0, 0
var hStdout = conHandle var hStdout = conHandle
if GetConsoleScreenBufferInfo(hStdout, addr(scrbuf)) == 0: if GetConsoleScreenBufferInfo(hStdout, addr(scrbuf)) == 0: