fixes strictdefs warnings (#24550)

(cherry picked from commit ce4304ce97)
This commit is contained in:
ringabout
2024-12-20 22:26:30 +08:00
committed by narimiran
parent 09835a1d9e
commit d96c5b2396
19 changed files with 148 additions and 126 deletions

View File

@@ -1440,7 +1440,7 @@ template findChild*(n: NimNode; cond: untyped): NimNode {.dirty.} =
## it.basename.ident == ident"foo")
## ```
block:
var res: NimNode
var res: NimNode = nil
for it in n.children:
if cond:
res = it

View File

@@ -1300,7 +1300,8 @@ else:
# `rwlist` associated with file descriptor MUST BE emptied before
# dispatching callback (See https://github.com/nim-lang/Nim/issues/5128),
# or it can be possible to fall into endless cycle.
var curList: seq[Callback]
result = (0, 0)
var curList: seq[Callback] = @[]
let selector = getGlobalDispatcher().selector
withData(selector, fd.int, fdData):
@@ -1352,7 +1353,7 @@ else:
# {Event.Timer, Event.Signal, Event.Process, Event.Vnode}.
# There can be only one callback registered with one descriptor,
# so there is no need to iterate over list.
var curList: seq[Callback]
var curList: seq[Callback] = @[]
withData(p.selector, fd.int, adata) do:
curList = move adata.readList
@@ -1550,7 +1551,7 @@ else:
var retFuture = newFuture[void]("sendTo")
# we will preserve address in our stack
var staddr: array[128, char] # SOCKADDR_STORAGE size is 128 bytes
var staddr {.noinit.} : array[128, char] # SOCKADDR_STORAGE size is 128 bytes
var stalen = saddrLen
zeroMem(addr(staddr[0]), 128)
copyMem(addr(staddr[0]), saddr, saddrLen)
@@ -1604,7 +1605,7 @@ else:
client: AsyncFD]]("acceptAddr")
proc cb(sock: AsyncFD): bool {.gcsafe.} =
result = true
var sockAddress: Sockaddr_storage
var sockAddress: Sockaddr_storage = default(Sockaddr_storage)
var addrLen = sizeof(sockAddress).SockLen
var client =
when declared(accept4):
@@ -2045,7 +2046,7 @@ when defined(linux) or defined(windows) or defined(macosx) or defined(bsd) or
elif defined(zephyr) or defined(freertos):
result = FD_MAX
else:
var fdLim: RLimit
var fdLim: RLimit = default(RLimit)
if getrlimit(RLIMIT_NOFILE, fdLim) < 0:
raiseOSError(osLastError())
result = int(fdLim.rlim_cur) - 1

View File

@@ -218,6 +218,7 @@ proc asyncSingleProc(prc: NimNode): NimNode =
elif returnType.kind == nnkEmpty:
baseType = returnType
else:
baseType = nil
verifyReturnType(repr(returnType), returnType)
let futureVarIdents = getFutureVarIdents(prc.params)

View File

@@ -850,7 +850,7 @@ proc sendTo*(socket: AsyncSocket, address: string, port: Port, data: string,
var
it = aiList
success = false
lastException: ref Exception
lastException: ref Exception = nil
while it != nil:
let fut = sendTo(socket.fd.AsyncFD, cstring(data), len(data), it.ai_addr,
@@ -921,10 +921,10 @@ proc recvFrom*(socket: AsyncSocket, data: FutureVar[string], size: int,
case socket.domain
of AF_INET6:
var sAddr: Sockaddr_in6
var sAddr: Sockaddr_in6 = default(Sockaddr_in6)
adaptRecvFromToDomain(AF_INET6)
of AF_INET:
var sAddr: Sockaddr_in
var sAddr: Sockaddr_in = default(Sockaddr_in)
adaptRecvFromToDomain(AF_INET)
else:
raise newException(ValueError, "Unknown socket address family")

View File

@@ -1961,6 +1961,7 @@ proc untilElementEnd(x: var XmlParser, result: XmlNode,
result.addNode(parse(x, errors))
proc parse(x: var XmlParser, errors: var seq[string]): XmlNode =
result = nil
case x.kind
of xmlComment:
result = newComment(x.rawData)
@@ -2017,7 +2018,7 @@ proc parseHtml*(s: Stream, filename: string,
errors: var seq[string]): XmlNode =
## Parses the XML from stream `s` and returns a `XmlNode`. Every
## occurred parsing error is added to the `errors` sequence.
var x: XmlParser
var x: XmlParser = default(XmlParser)
open(x, s, filename, {reportComments, reportWhitespace, allowUnquotedAttribs,
allowEmptyAttribs})
next(x)

View File

@@ -1035,6 +1035,7 @@ proc format(entry: MultipartEntry, boundary: string): string =
proc format(client: HttpClient | AsyncHttpClient,
multipart: MultipartData): Future[seq[string]] {.multisync.} =
result = @[]
let bound = getBoundary(multipart)
client.headers["Content-Type"] = "multipart/form-data; boundary=" & bound

View File

@@ -291,11 +291,12 @@ proc getAddrInfo*(address: string, port: Port, domain: Domain = AF_INET,
##
##
## .. warning:: The resulting `ptr AddrInfo` must be freed using `freeAddrInfo`!
var hints: AddrInfo
var hints: AddrInfo = AddrInfo(
ai_family: toInt(domain),
ai_socktype: toInt(sockType),
ai_protocol: toInt(protocol)
)
result = nil
hints.ai_family = toInt(domain)
hints.ai_socktype = toInt(sockType)
hints.ai_protocol = toInt(protocol)
# OpenBSD doesn't support AI_V4MAPPED and doesn't define the macro AI_V4MAPPED.
# FreeBSD, Haiku don't support AI_V4MAPPED but defines the macro.
# https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=198092
@@ -343,7 +344,7 @@ template htons*(x: uint16): untyped =
proc getSockDomain*(socket: SocketHandle): Domain =
## Returns the socket's domain (AF_INET or AF_INET6).
var name: Sockaddr_in6
var name: Sockaddr_in6 = default(Sockaddr_in6)
var namelen = sizeof(name).SockLen
if getsockname(socket, cast[ptr SockAddr](addr(name)),
addr(namelen)) == -1'i32:
@@ -366,10 +367,12 @@ when not useNimNetLite:
else:
var s = posix.getservbyname(name, proto)
if s == nil: raiseOSError(osLastError(), "Service not found.")
result.name = $s.s_name
result.aliases = cstringArrayToSeq(s.s_aliases)
result.port = Port(s.s_port)
result.proto = $s.s_proto
result = Servent(
name: $s.s_name,
aliases: cstringArrayToSeq(s.s_aliases),
port: Port(s.s_port),
proto: $s.s_proto
)
proc getServByPort*(port: Port, proto: string): Servent {.tags: [ReadIOEffect].} =
## Searches the database from the beginning and finds the first entry for
@@ -382,10 +385,12 @@ when not useNimNetLite:
else:
var s = posix.getservbyport(uint16(port).cint, proto)
if s == nil: raiseOSError(osLastError(), "Service not found.")
result.name = $s.s_name
result.aliases = cstringArrayToSeq(s.s_aliases)
result.port = Port(s.s_port)
result.proto = $s.s_proto
result = Servent(
name: $s.s_name,
aliases: cstringArrayToSeq(s.s_aliases),
port: Port(s.s_port),
proto: $s.s_proto
)
proc getHostByAddr*(ip: string): Hostent {.tags: [ReadIOEffect].} =
## This function will lookup the hostname of an IP Address.
@@ -423,8 +428,10 @@ when not useNimNetLite:
if s == nil:
raiseOSError(osLastError(), $hstrerror(h_errno))
result.name = $s.h_name
result.aliases = cstringArrayToSeq(s.h_aliases)
result = Hostent(
name: $s.h_name,
aliases: cstringArrayToSeq(s.h_aliases)
)
when useWinVersion:
result.addrtype = Domain(s.h_addrtype)
else:
@@ -465,8 +472,10 @@ when not useNimNetLite:
else:
var s = posix.gethostbyname(name)
if s == nil: raiseOSError(osLastError())
result.name = $s.h_name
result.aliases = cstringArrayToSeq(s.h_aliases)
result = Hostent(
name: $s.h_name,
aliases: cstringArrayToSeq(s.h_aliases)
)
when useWinVersion:
result.addrtype = Domain(s.h_addrtype)
else:
@@ -566,14 +575,14 @@ when not useNimNetLite:
when defined(posix) and not defined(nimdoc):
proc makeUnixAddr*(path: string): Sockaddr_un =
result.sun_family = AF_UNIX.TSa_Family
result = Sockaddr_un(sun_family: AF_UNIX.TSa_Family)
if path.len >= Sockaddr_un_path_length:
raise newException(ValueError, "socket path too long")
copyMem(addr result.sun_path, path.cstring, path.len + 1)
proc getSockName*(socket: SocketHandle): Port =
## Returns the socket's associated port number.
var name: Sockaddr_in
var name: Sockaddr_in = default(Sockaddr_in)
when useWinVersion:
name.sin_family = uint16(ord(AF_INET))
else:
@@ -590,9 +599,10 @@ when not useNimNetLite:
## Returns the socket's local address and port number.
##
## Similar to POSIX's `getsockname`:idx:.
result = default((string, Port))
case domain
of AF_INET:
var name: Sockaddr_in
var name: Sockaddr_in = default(Sockaddr_in)
when useWinVersion:
name.sin_family = uint16(ord(AF_INET))
else:
@@ -604,7 +614,7 @@ when not useNimNetLite:
result = ($inet_ntoa(name.sin_addr),
Port(nativesockets.ntohs(name.sin_port)))
of AF_INET6:
var name: Sockaddr_in6
var name: Sockaddr_in6 = default(Sockaddr_in6)
when useWinVersion:
name.sin6_family = uint16(ord(AF_INET6))
else:
@@ -627,9 +637,10 @@ when not useNimNetLite:
## Returns the socket's peer address and port number.
##
## Similar to POSIX's `getpeername`:idx:
result = default((string, Port))
case domain
of AF_INET:
var name: Sockaddr_in
var name: Sockaddr_in = default(Sockaddr_in)
when useWinVersion:
name.sin_family = uint16(ord(AF_INET))
else:
@@ -641,7 +652,7 @@ when not useNimNetLite:
result = ($inet_ntoa(name.sin_addr),
Port(nativesockets.ntohs(name.sin_port)))
of AF_INET6:
var name: Sockaddr_in6
var name: Sockaddr_in6 = default(Sockaddr_in6)
when useWinVersion:
name.sin6_family = uint16(ord(AF_INET6))
else:
@@ -735,7 +746,7 @@ when useNimNetLite:
proc getSockOptInt*(socket: SocketHandle, level, optname: int): int {.
tags: [ReadIOEffect].} =
## getsockopt for integer options.
var res: cint
var res: cint = cint(0)
var size = sizeof(res).SockLen
if getsockopt(socket, cint(level), cint(optname),
addr(res), addr(size)) < 0'i32:
@@ -768,6 +779,8 @@ proc setBlocking*(s: SocketHandle, blocking: bool) =
raiseOSError(osLastError())
proc timeValFromMilliseconds(timeout = 500): Timeval =
## Converts a timeout in milliseconds to a Timeval.
result = default(Timeval)
if timeout != -1:
var seconds = timeout div 1000
when useWinVersion:
@@ -804,7 +817,7 @@ proc selectRead*(readfds: var seq[SocketHandle], timeout = 500): int =
## an unlimited time.
var tv {.noinit.}: Timeval = timeValFromMilliseconds(timeout)
var rd: TFdSet
var rd: TFdSet = default(TFdSet)
var m = 0
createFdSet((rd), readfds, m)
@@ -826,7 +839,7 @@ proc selectWrite*(writefds: var seq[SocketHandle],
## an unlimited time.
var tv {.noinit.}: Timeval = timeValFromMilliseconds(timeout)
var wr: TFdSet
var wr: TFdSet = default(TFdSet)
var m = 0
createFdSet((wr), writefds, m)
@@ -844,7 +857,7 @@ proc accept*(fd: SocketHandle, inheritable = defined(nimInheritHandles)): (Socke
## child processes.
##
## Returns (osInvalidSocket, "") if an error occurred.
var sockAddress: SockAddr
var sockAddress: SockAddr = default(SockAddr)
var addrLen = sizeof(sockAddress).SockLen
var sock =
when (defined(linux) or defined(bsd)) and not defined(nimdoc):

View File

@@ -212,7 +212,7 @@ when defined(posix) and not defined(lwip):
from std/posix import TPollfd, POLLIN, POLLPRI, POLLOUT, POLLWRBAND, Tnfds
template monitorPollEvent(x: var SocketHandle, y, timeout: cint): int =
var tpollfd: TPollfd
var tpollfd: TPollfd = default(TPollfd)
tpollfd.fd = cast[cint](x)
tpollfd.events = y
posix.poll(addr(tpollfd), Tnfds(1), timeout)
@@ -255,6 +255,7 @@ proc isDisconnectionError*(flags: set[SocketFlag],
proc toOSFlags*(socketFlags: set[SocketFlag]): cint =
## Converts the flags into the underlying OS representation.
result = cint(0)
for f in socketFlags:
case f
of SocketFlag.Peek:
@@ -1031,7 +1032,7 @@ proc bindAddr*(socket: Socket, port = Port(0), address = "") {.
var aiList = getAddrInfo(realaddr, port, socket.domain)
if bindAddr(socket.fd, aiList.ai_addr, aiList.ai_addrlen.SockLen) < 0'i32:
freeAddrInfo(aiList)
var address2: string
var address2: string = ""
address2.addQuoted address
raiseOSError(osLastError(), "address: $# port: $#" % [address2, $port])
freeAddrInfo(aiList)
@@ -1478,7 +1479,7 @@ proc waitFor(socket: Socket, waited: var Duration, timeout, size: int,
proc recv*(socket: Socket, data: pointer, size: int, timeout: int): int {.
tags: [ReadIOEffect, TimeEffect].} =
## overload with a `timeout` parameter in milliseconds.
var waited: Duration # duration already waited
var waited: Duration = default(Duration) # duration already waited
var read = 0
while read < size:
@@ -1605,7 +1606,7 @@ proc readLine*(socket: Socket, line: var string, timeout = -1,
socket.socketError(n, lastError = lastError, flags = flags)
return
var waited: Duration
var waited: Duration = default(Duration) # duration already waited
setLen(line, 0)
while true:
@@ -1708,7 +1709,7 @@ proc skip*(socket: Socket, size: int, timeout = -1) =
## bytes takes longer than specified a TimeoutError exception will be raised.
##
## Returns the number of skipped bytes.
var waited: Duration
var waited: Duration = default(Duration) # duration already waited
var dummy = alloc(size)
var bytesSkipped = 0
while bytesSkipped != size:
@@ -1838,8 +1839,8 @@ proc sendTo*(socket: Socket, address: IpAddress, port: Port,
assert(socket.protocol != IPPROTO_TCP, "Cannot `sendTo` on a TCP socket")
assert(not socket.isClosed, "Cannot `sendTo` on a closed socket")
var sa: Sockaddr_storage
var sl: SockLen
var sa: Sockaddr_storage = default(Sockaddr_storage)
var sl: SockLen = default(SockLen)
toSockAddr(address, port, sa, sl)
result = sendto(socket.fd, cstring(data), data.len().cint, flags.cint,
cast[ptr SockAddr](addr sa), sl)
@@ -1998,7 +1999,7 @@ proc dial*(address: string, port: Port,
let aiList = getAddrInfo(address, port, AF_UNSPEC, sockType, protocol)
var fdPerDomain: array[low(Domain).ord..high(Domain).ord, SocketHandle]
var fdPerDomain = default(array[low(Domain).ord..high(Domain).ord, SocketHandle])
for i in low(fdPerDomain)..high(fdPerDomain):
fdPerDomain[i] = osInvalidSocket
template closeUnusedFds(domainToKeep = -1) {.dirty.} =
@@ -2007,10 +2008,10 @@ proc dial*(address: string, port: Port,
fd.close()
var success = false
var lastError: OSErrorCode
var lastError: OSErrorCode = default(OSErrorCode)
var it = aiList
var domain: Domain
var lastFd: SocketHandle
var domain: Domain = default(Domain)
var lastFd: SocketHandle = default(SocketHandle)
while it != nil:
let domainOpt = it.ai_family.toKnownDomain()
if domainOpt.isNone:
@@ -2041,6 +2042,7 @@ proc dial*(address: string, port: Port,
result = newSocket(lastFd, domain, sockType, protocol, buffered)
elif lastError != 0.OSErrorCode:
lastFd.close()
result = default(Socket)
raiseOSError(lastError)
else:
lastFd.close()
@@ -2057,7 +2059,7 @@ proc connect*(socket: Socket, address: string,
var aiList = getAddrInfo(address, port, socket.domain)
# try all possibilities:
var success = false
var lastError: OSErrorCode
var lastError: OSErrorCode = default(OSErrorCode)
var it = aiList
while it != nil:
if connect(socket.fd, it.ai_addr, it.ai_addrlen.SockLen) == 0'i32:
@@ -2097,7 +2099,7 @@ proc connectAsync(socket: Socket, name: string, port = Port(0),
var aiList = getAddrInfo(name, port, af)
# try all possibilities:
var success = false
var lastError: OSErrorCode
var lastError: OSErrorCode = default(OSErrorCode)
var it = aiList
while it != nil:
var ret = connect(socket.fd, it.ai_addr, it.ai_addrlen.SockLen)

View File

@@ -421,6 +421,7 @@ proc expandFilename*(filename: string): string {.rtl, extern: "nos$1",
## Returns the full (`absolute`:idx:) path of an existing file `filename`.
##
## Raises `OSError` in case of an error. Follows symlinks.
result = ""
when defined(windows):
var bufsize = MAX_PATH.int32
var unused: WideCString = nil
@@ -452,7 +453,9 @@ proc expandFilename*(filename: string): string {.rtl, extern: "nos$1",
result = $r
c_free(cast[pointer](r))
proc getCurrentCompilerExe*(): string {.compileTime.} = discard
proc getCurrentCompilerExe*(): string {.compileTime.} =
result = ""
discard "implemented in the vmops"
## Returns the path of the currently running Nim compiler or nimble executable.
##
## Can be used to retrieve the currently executing
@@ -838,6 +841,7 @@ proc getFileInfo*(handle: FileHandle): FileInfo {.noWeirdTarget.} =
## * `getFileInfo(path, followSymlink) proc`_
# Done: ID, Kind, Size, Permissions, Link Count
result = default(FileInfo)
when defined(windows):
var rawInfo: BY_HANDLE_FILE_INFORMATION
# We have to use the super special '_get_osfhandle' call (wrapped above)
@@ -847,7 +851,7 @@ proc getFileInfo*(handle: FileHandle): FileInfo {.noWeirdTarget.} =
raiseOSError(osLastError(), $handle)
rawToFormalFileInfo(rawInfo, "", result)
else:
var rawInfo: Stat
var rawInfo: Stat = default(Stat)
if fstat(handle, rawInfo) < 0'i32:
raiseOSError(osLastError(), $handle)
rawToFormalFileInfo(rawInfo, "", result)
@@ -909,6 +913,7 @@ proc sameFileContent*(path1, path2: string): bool {.rtl, extern: "nos$1",
##
## See also:
## * `sameFile proc`_
result = false
var
a, b: File = default(File)
if not open(a, path1): return false

View File

@@ -351,7 +351,7 @@ proc execProcesses*(cmds: openArray[string],
##
## The highest (absolute) return value of all processes is returned.
## Runs `beforeRunEvent` before running each command.
result = 0
assert n > 0
if n > 1:
var i = 0
@@ -506,6 +506,7 @@ proc readLines*(p: Process): (seq[string], int) {.since: (1, 3),
## for line in lines: echo line
## p.close
## ```
result = (@[], 0)
for line in p.lines: result[0].add(line)
result[1] = p.peekExitCode
@@ -961,7 +962,7 @@ elif not defined(useNimRtl):
options: set[ProcessOption] = {poStdErrToStdOut}):
owned Process =
var
pStdin, pStdout, pStderr: array[0..1, cint]
pStdin, pStdout, pStderr: array[0..1, cint] = default(array[0..1, cint])
new(result)
result.options = options
result.exitFlag = true
@@ -971,7 +972,7 @@ elif not defined(useNimRtl):
pipe(pStderr) != 0'i32:
raiseOSError(osLastError())
var data: StartProcessData
var data: StartProcessData = default(StartProcessData)
var sysArgsRaw: seq[string]
if poEvalCommand in options:
const useShPath {.strdefine.} =
@@ -1121,7 +1122,7 @@ elif not defined(useNimRtl):
discard close(data.pErrorPipe[writeIdx])
if pid < 0: raiseOSError(osLastError())
var error: cint
var error: cint = cint(0)
let sizeRead = read(data.pErrorPipe[readIdx], addr error, sizeof(error))
if sizeRead == sizeof(error):
raiseOSError(OSErrorCode(error),
@@ -1167,7 +1168,7 @@ elif not defined(useNimRtl):
if (poUsePath in data.options):
when defined(uClibc) or defined(linux) or defined(haiku):
# uClibc environment (OpenWrt included) doesn't have the full execvpe
var exe: string
var exe: string = ""
try:
exe = findExe(data.sysCommand)
except OSError as e:
@@ -1223,6 +1224,7 @@ elif not defined(useNimRtl):
elif ret == 0:
return true # Can't establish status. Assume running.
else:
result = false
raiseOSError(osLastError())
proc terminate(p: Process) =
@@ -1368,7 +1370,7 @@ elif not defined(useNimRtl):
# Backwards compatibility with previous verison to
# handle cases where timeout == -1, but extend
# to handle cases where timeout < 0
var status: cint
var status: cint = cint(0)
if waitpid(p.id, status, 0) < 0:
raiseOSError(osLastError())
p.exitFlag = true
@@ -1382,7 +1384,7 @@ elif not defined(useNimRtl):
var delay = initDuration(microseconds = 50)
while true:
var status: cint
var status: cint = cint(0)
let pid = waitpid(p.id, status, WNOHANG)
if p.id == pid :
p.exitFlag = true
@@ -1407,8 +1409,8 @@ elif not defined(useNimRtl):
ns = ticks mod max
secs = ticks div max
var
waitSpec: TimeSpec
unused: Timespec
waitSpec: TimeSpec = default(TimeSpec)
unused: Timespec = default(Timespec)
waitSpec.tv_sec = posix.Time(secs)
waitSpec.tv_nsec = clong ns
discard posix.clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, waitSpec, unused)
@@ -1432,7 +1434,7 @@ elif not defined(useNimRtl):
proc createStream(handle: var FileHandle,
fileMode: FileMode): owned FileStream =
var f: File
var f: File = default(File)
if not open(f, handle, fileMode): raiseOSError(osLastError())
return newFileStream(f)
@@ -1494,11 +1496,9 @@ elif not defined(useNimRtl):
setLen(s, L)
proc select(readfds: var seq[Process], timeout = 500): int =
var tv: Timeval
tv.tv_sec = posix.Time(0)
tv.tv_usec = Suseconds(timeout * 1000)
var tv: Timeval = Timeval(tv_sec: posix.Time(0), tv_usec: Suseconds(timeout * 1000))
var rd: TFdSet
var rd: TFdSet = default(TFdSet)
var m = 0
createFdSet((rd), readfds, m)
@@ -1510,7 +1510,7 @@ elif not defined(useNimRtl):
pruneProcessSet(readfds, (rd))
proc hasData*(p: Process): bool =
var rd: TFdSet
var rd: TFdSet = default(TFdSet)
FD_ZERO(rd)
let m = max(0, int(p.outHandle))

View File

@@ -584,7 +584,7 @@ proc add*(father, n: SqlNode) =
proc getTok(p: var SqlParser) =
getTok(p, p.tok)
proc sqlError(p: SqlParser, msg: string) =
proc sqlError(p: SqlParser, msg: string) {.noreturn.} =
var e: ref SqlParseError
new(e)
e.msg = errorStr(p, msg)
@@ -683,6 +683,7 @@ proc parseExpr(p: var SqlParser): SqlNode {.gcsafe.}
proc parseSelect(p: var SqlParser): SqlNode {.gcsafe.}
proc identOrLiteral(p: var SqlParser): SqlNode =
result = nil
case p.tok.kind
of tkQuotedIdentifier:
result = newNode(nkQuotedIdent, p.tok.literal)
@@ -719,7 +720,7 @@ proc identOrLiteral(p: var SqlParser): SqlNode =
getTok(p)
else:
sqlError(p, "expression expected")
getTok(p) # we must consume a token here to prevent endless loops!
# getTok(p) # we must consume a token here to prevent endless loops!
proc primary(p: var SqlParser): SqlNode =
if (p.tok.kind == tkOperator and (p.tok.literal == "+" or p.tok.literal ==
@@ -760,7 +761,7 @@ proc primary(p: var SqlParser): SqlNode =
getTok(p)
else: break
proc lowestExprAux(p: var SqlParser, v: var SqlNode, limit: int): int =
proc lowestExprAux(p: var SqlParser, v: out SqlNode, limit: int): int =
var
v2, node, opNode: SqlNode
v = primary(p) # expand while operators have priorities higher than 'limit'
@@ -1531,9 +1532,7 @@ proc ra(n: SqlNode, s: var SqlWriter) =
proc renderSql*(n: SqlNode, upperCase = false): string =
## Converts an SQL abstract syntax tree to its string representation.
var s: SqlWriter
s.buffer = ""
s.upperCase = upperCase
var s = SqlWriter(buffer: "", upperCase: upperCase)
ra(n, s)
return s.buffer
@@ -1575,8 +1574,7 @@ proc parseSql*(input: Stream, filename: string, considerTypeParams = false): Sql
## parses the SQL from `input` into an AST and returns the AST.
## `filename` is only used for error messages.
## Syntax errors raise an `SqlParseError` exception.
var p: SqlParser
p.considerTypeParams = considerTypeParams
var p: SqlParser = SqlParser(considerTypeParams: considerTypeParams)
open(p, input, filename)
try:
result = parse(p)

View File

@@ -234,8 +234,7 @@ func `*`*(a: Peg): Peg {.rtl, extern: "npegsGreedyRep".} =
## constructs a "greedy repetition" for the PEG `a`
case a.kind
of pkGreedyRep, pkGreedyRepChar, pkGreedyRepSet, pkGreedyAny, pkOption:
assert false
# produces endless loop!
raiseAssert "unreachable" # produces endless loop!
of pkChar:
result = Peg(kind: pkGreedyRepChar, ch: a.ch)
of pkCharChoice:
@@ -334,7 +333,7 @@ func backrefIgnoreStyle*(index: range[1..MaxSubpatterns], reverse: bool = false)
func spaceCost(n: Peg): int =
case n.kind
of pkEmpty: discard
of pkEmpty: result = 0
of pkTerminal, pkTerminalIgnoreCase, pkTerminalIgnoreStyle, pkChar,
pkGreedyRepChar, pkCharChoice, pkGreedyRepSet,
pkAny..pkWhitespace, pkGreedyAny, pkBackRef..pkBackRefIgnoreStyle:
@@ -343,6 +342,7 @@ func spaceCost(n: Peg): int =
# we cannot inline a rule with a non-terminal
result = InlineThreshold+1
else:
result = 0
for i in 0..n.len-1:
inc(result, spaceCost(n.sons[i]))
if result >= InlineThreshold: break
@@ -1087,8 +1087,7 @@ func matchLen*(s: string, pattern: Peg, matches: var openArray[string],
## if there is no match, -1 is returned. Note that a match length
## of zero can happen. It's possible that a suffix of `s` remains
## that does not belong to the match.
var c: Captures
c.origStart = start
var c: Captures = Captures(origStart: start)
result = rawMatch(s, pattern, start, c)
if result >= 0: fillMatches(s, matches, c)
@@ -1098,8 +1097,7 @@ func matchLen*(s: string, pattern: Peg,
## if there is no match, -1 is returned. Note that a match length
## of zero can happen. It's possible that a suffix of `s` remains
## that does not belong to the match.
var c: Captures
c.origStart = start
var c: Captures = Captures(origStart: start)
result = rawMatch(s, pattern, start, c)
func match*(s: string, pattern: Peg, matches: var openArray[string],
@@ -1121,8 +1119,7 @@ func find*(s: string, pattern: Peg, matches: var openArray[string],
## returns the starting position of ``pattern`` in ``s`` and the captured
## substrings in the array ``matches``. If it does not match, nothing
## is written into ``matches`` and -1 is returned.
var c: Captures
c.origStart = start
var c: Captures = Captures(origStart: start)
for i in start .. s.len-1:
c.ml = 0
if rawMatch(s, pattern, i, c) >= 0:
@@ -1138,8 +1135,7 @@ func findBounds*(s: string, pattern: Peg, matches: var openArray[string],
## and the captured
## substrings in the array ``matches``. If it does not match, nothing
## is written into ``matches`` and (-1,0) is returned.
var c: Captures
c.origStart = start
var c: Captures = Captures(origStart: start)
for i in start .. s.len-1:
c.ml = 0
var L = rawMatch(s, pattern, i, c)
@@ -1152,16 +1148,14 @@ func find*(s: string, pattern: Peg,
start = 0): int {.rtl, extern: "npegs$1".} =
## returns the starting position of ``pattern`` in ``s``. If it does not
## match, -1 is returned.
var c: Captures
c.origStart = start
var c: Captures = Captures(origStart: start)
for i in start .. s.len-1:
if rawMatch(s, pattern, i, c) >= 0: return i
return -1
iterator findAll*(s: string, pattern: Peg, start = 0): string =
## yields all matching *substrings* of `s` that match `pattern`.
var c: Captures
c.origStart = start
var c: Captures = Captures(origStart: start)
var i = start
while i < s.len:
c.ml = 0
@@ -1221,8 +1215,8 @@ func startsWith*(s: string, prefix: Peg, start = 0): bool {.
func endsWith*(s: string, suffix: Peg, start = 0): bool {.
rtl, extern: "npegs$1".} =
## returns true if `s` ends with the pattern `suffix`
var c: Captures
c.origStart = start
result = false
var c: Captures = Captures(origStart: start)
for i in start .. s.len-1:
if rawMatch(s, suffix, i, c) == s.len - i: return true
@@ -1242,8 +1236,8 @@ func replacef*(s: string, sub: Peg, by: string): string {.
## ```
result = ""
var i = 0
var caps: array[0..MaxSubpatterns-1, string]
var c: Captures
var caps: array[0..MaxSubpatterns-1, string] = default(array[0..MaxSubpatterns-1, string])
var c: Captures = default(Captures)
while i < s.len:
c.ml = 0
var x = rawMatch(s, sub, i, c)
@@ -1262,7 +1256,7 @@ func replace*(s: string, sub: Peg, by = ""): string {.
## in `by`.
result = ""
var i = 0
var c: Captures
var c: Captures = default(Captures)
while i < s.len:
var x = rawMatch(s, sub, i, c)
if x <= 0:
@@ -1280,8 +1274,8 @@ func parallelReplace*(s: string, subs: varargs[
## applied in parallel.
result = ""
var i = 0
var c: Captures
var caps: array[0..MaxSubpatterns-1, string]
var c: Captures = default(Captures)
var caps: array[0..MaxSubpatterns-1, string] = default(array[0..MaxSubpatterns-1, string])
while i < s.len:
block searchSubs:
for j in 0..high(subs):
@@ -1328,8 +1322,8 @@ func replace*(s: string, sub: Peg, cb: proc(
## ```
result = ""
var i = 0
var caps: array[0..MaxSubpatterns-1, string]
var c: Captures
var caps: array[0..MaxSubpatterns-1, string] = default(array[0..MaxSubpatterns-1, string])
var c: Captures = default(Captures)
var m = 0
while i < s.len:
c.ml = 0
@@ -1376,7 +1370,7 @@ iterator split*(s: string, sep: Peg): string =
## "an"
## "example"
## ```
var c: Captures
var c: Captures = default(Captures)
var
first = 0
last = 0
@@ -1826,7 +1820,7 @@ type
identIsVerbatim: bool
skip: Peg
func pegError(p: PegParser, msg: string, line = -1, col = -1) =
func pegError(p: PegParser, msg: string, line = -1, col = -1) {.noreturn.} =
var e = (ref EInvalidPeg)(msg: errorStr(p, msg, line, col))
raise e
@@ -1966,7 +1960,7 @@ func primary(p: var PegParser): Peg =
getTok(p)
else:
pegError(p, "expression expected, but found: " & p.tok.literal)
getTok(p) # we must consume a token here to prevent endless loops!
# getTok(p) # we must consume a token here to prevent endless loops!
while true:
case p.tok.kind
of tkOption:
@@ -2050,7 +2044,7 @@ func parsePeg*(pattern: string, filename = "pattern", line = 1, col = 0): Peg =
## constructs a Peg object from `pattern`. `filename`, `line`, `col` are
## used for error messages, but they only provide start offsets. `parsePeg`
## keeps track of line and column numbers within `pattern`.
var p: PegParser
var p: PegParser = default(PegParser)
init(PegLexer(p), pattern, filename, line, col)
p.tok.kind = tkInvalid
p.tok.modifier = modNone

View File

@@ -362,7 +362,7 @@ when not defined(js) and not defined(nimscript):
proc equalsFile*(r: Rope, f: File): bool {.rtl, extern: "nro$1File".} =
## Returns true if the contents of the file `f` equal `r`.
var
buf: array[bufSize, char] = default(array[bufSize, char])
buf {.noinit.}: array[bufSize, char]
bpos = buf.len
blen = buf.len

View File

@@ -260,7 +260,7 @@ else:
import std/[termios, posix, os, parseutils]
proc setRaw(fd: FileHandle, time: cint = TCSAFLUSH) =
var mode: Termios
var mode: Termios = default(Termios)
discard fd.tcGetAttr(addr mode)
mode.c_iflag = mode.c_iflag and not Cflag(BRKINT or ICRNL or INPCK or
ISTRIP or IXON)
@@ -277,8 +277,8 @@ else:
var
xStr = ""
yStr = ""
ch: char
ct: int
ch: char = '\0'
ct: int = 0
readX = false
# use raw mode to ask terminal for cursor position
@@ -316,7 +316,7 @@ else:
proc terminalWidthIoctl*(fds: openArray[int]): int =
## Returns terminal width from first fd that supports the ioctl.
var win: IOctl_WinSize
var win: IOctl_WinSize = default(IOctl_WinSize)
for fd in fds:
if ioctl(cint(fd), TIOCGWINSZ, addr win) != -1:
return int(win.ws_col)
@@ -325,7 +325,7 @@ else:
proc terminalHeightIoctl*(fds: openArray[int]): int =
## Returns terminal height from first fd that supports the ioctl.
var win: IOctl_WinSize
var win: IOctl_WinSize = default(IOctl_WinSize)
for fd in fds:
if ioctl(cint(fd), TIOCGWINSZ, addr win) != -1:
return int(win.ws_row)
@@ -349,7 +349,7 @@ else:
# unrelated to the terminal characteristics.
# See POSIX Base Definitions Section 8.1 Environment Variable Definition
var w: int
var w: int = 0
var s = getEnv("COLUMNS") # Try standard env var
if len(s) > 0 and parseSaturatedNatural(s, w) > 0 and w > 0:
return w
@@ -383,7 +383,7 @@ else:
# unrelated to the terminal characteristics.
# See POSIX Base Definitions Section 8.1 Environment Variable Definition
var h: int
var h: int = 0
var s = getEnv("LINES") # Try standard env var
if len(s) > 0 and parseSaturatedNatural(s, h) > 0 and h > 0:
return h
@@ -928,7 +928,7 @@ else:
bool {.tags: [ReadIOEffect, WriteIOEffect].} =
password.setLen(0)
let fd = stdin.getFileHandle()
var cur, old: Termios
var cur, old: Termios = default(Termios)
discard fd.tcGetAttr(cur.addr)
old = cur
cur.c_lflag = cur.c_lflag and not Cflag(ECHO)

View File

@@ -2255,9 +2255,10 @@ proc parse*(input: string, f: TimeFormat, zone: Timezone = local(),
let f = initTimeFormat("yyyy-MM-dd")
let dt = dateTime(2000, mJan, 01, 00, 00, 00, 00, utc())
doAssert dt == "2000-01-01".parse(f, utc())
result = default(DateTime)
var inpIdx = 0 # Input index
var patIdx = 0 # Pattern index
var parsed: ParsedTime
var parsed: ParsedTime = default(ParsedTime)
while inpIdx <= input.high and patIdx <= f.patterns.high:
let pattern = f.patterns[patIdx].FormatPattern
case pattern
@@ -2352,9 +2353,9 @@ proc `$`*(time: Time): string {.tags: [], raises: [], benign.} =
# TimeInterval
#
proc initTimeInterval*(nanoseconds, microseconds, milliseconds,
seconds, minutes, hours,
days, weeks, months, years: int = 0): TimeInterval =
proc initTimeInterval*(nanoseconds = 0, microseconds = 0, milliseconds = 0,
seconds = 0, minutes = 0, hours = 0,
days = 0, weeks = 0, months = 0, years = 0): TimeInterval =
## Creates a new `TimeInterval <#TimeInterval>`_.
##
## This proc doesn't perform any normalization! For example,
@@ -2847,7 +2848,7 @@ when not defined(js):
when defined(posix) and not defined(osx) and declared(CLOCK_THREAD_CPUTIME_ID):
# 'clocksPerSec' is a compile-time constant, possibly a
# rather awful one, so use clock_gettime instead
var ts: Timespec
var ts: Timespec = default(Timespec)
discard clock_gettime(CLOCK_THREAD_CPUTIME_ID, ts)
result = toFloat(ts.tv_sec.int) +
toFloat(ts.tv_nsec.int) / 1_000_000_000

View File

@@ -47,14 +47,15 @@ template call(f) =
raiseOSError(err.OSErrorCode, astToStr(f))
proc getUnicodeValue*(path, key: string; handle: HKEY): string =
result = ""
let hh = newWideCString path
let kk = newWideCString key
var bufSize: int32
var bufSize: int32 = int32(0)
# try a couple of different flag settings:
var flags: int32 = RRF_RT_ANY
let err = regGetValue(handle, hh, kk, flags, nil, nil, addr bufSize)
if err != 0:
var newHandle: HKEY
var newHandle: HKEY = default(HKEY)
call regOpenKeyEx(handle, hh, 0, KEY_READ or KEY_WOW64_64KEY, newHandle)
call regGetValue(newHandle, nil, kk, flags, nil, nil, addr bufSize)
if bufSize > 0:

View File

@@ -843,7 +843,7 @@ proc inet_ntop_emulated(family: cint, paddr: pointer, pStringBuffer: cstring,
stringBufSize: int32): cstring {.stdcall.} =
case family
of AF_INET:
var sa: Sockaddr_in
var sa: Sockaddr_in = default(Sockaddr_in)
sa.sin_family = AF_INET
sa.sin_addr = cast[ptr InAddr](paddr)[]
var bs = stringBufSize.DWORD
@@ -853,7 +853,7 @@ proc inet_ntop_emulated(family: cint, paddr: pointer, pStringBuffer: cstring,
else:
result = pStringBuffer
of AF_INET6:
var sa: Sockaddr_in6
var sa: Sockaddr_in6 = default(Sockaddr_in6)
sa.sin6_family = AF_INET6
sa.sin6_addr = cast[ptr In6_addr](paddr)[]
var bs = stringBufSize.DWORD
@@ -868,7 +868,7 @@ proc inet_ntop_emulated(family: cint, paddr: pointer, pStringBuffer: cstring,
proc inet_ntop*(family: cint, paddr: pointer, pStringBuffer: cstring,
stringBufSize: int32): cstring {.stdcall.} =
var ver: OSVERSIONINFO
var ver: OSVERSIONINFO = default(OSVERSIONINFO)
ver.dwOSVersionInfoSize = sizeof(ver).DWORD
let res = getVersionExW(ver.addr)
if res == 0:

View File

@@ -65,7 +65,7 @@ when not defined(windows):
if ret.line.len > 0: echo ret.line
if ret.status == lnCtrlD: break
echo "exiting"
var data: LinenoiseData
var data: LinenoiseData = default(LinenoiseData)
let buf = linenoiseExtra(prompt, data.addr)
result.line = $buf
free(buf)

View File

@@ -366,6 +366,8 @@ else:
result = symAddr(dll, name)
if result.isNil and alternativeName.len > 0:
result = symAddr(dll, alternativeName)
else:
result = nil
# Attempt to load from current exe.
if result.isNil:
@@ -402,6 +404,7 @@ else:
proc SSL_library_init*(): cint {.discardable.} =
## Initialize SSL using OPENSSL_init_ssl for OpenSSL >= 1.1.0 otherwise
## SSL_library_init
result = cint(0)
let newInitSym = sslSymNullable("OPENSSL_init_ssl")
if not newInitSym.isNil:
let newInitProc =
@@ -557,6 +560,7 @@ proc i2d_X509*(cert: PX509; o: ptr ptr uint8): cint {.cdecl,
proc d2i_X509*(b: string): PX509 =
## decode DER/BER bytestring into X.509 certificate struct
result = default(PX509)
var bb = b.cstring
let i = cast[ptr ptr uint8](addr bb)
let ret = d2i_X509(addr result, i, b.len.cint)
@@ -795,8 +799,8 @@ proc md5_File*(file: string): string {.raises: [IOError,Exception].} =
sz = 512
let f = open(file,fmRead)
var
buf: array[sz,char]
ctx: MD5_CTX
buf: array[sz, char] = default(array[sz, char])
ctx: MD5_CTX = default(MD5_CTX)
discard md5_Init(ctx)
while (let bytes = f.readChars(buf); bytes > 0):
@@ -811,7 +815,7 @@ proc md5_Str*(str: string): string =
## Generate MD5 hash for a string. Result is a 32 character
## hex string with lowercase characters
var
ctx: MD5_CTX
ctx: MD5_CTX = default(MD5_CTX)
res: array[MD5_DIGEST_LENGTH,char]
input = str.cstring
discard md5_Init(ctx)