fixes strictdefs warnings for stdlibs [part two] (#24514)

After some cleanups for stdlibs, then we should enable warningaserror
for all tests

(cherry picked from commit c0861142f8)
This commit is contained in:
ringabout
2024-12-06 12:40:48 +08:00
committed by narimiran
parent 94a6b85538
commit 2d470c9afd
44 changed files with 162 additions and 92 deletions

View File

@@ -44,6 +44,9 @@ runnableExamples:
assert mcCounter.value == 3
when defined(nimPreviewSlimSystem):
import std/assertions
type
CacheSeq* = distinct string
## Compile-time sequence of `NimNode`s.
@@ -207,7 +210,7 @@ proc hasKey*(t: CacheTable; key: string): bool =
mcTable["foo"] = newEmptyNode()
# Will now be true since we inserted a value
assert mcTable.hasKey("foo")
discard "Implemented in vmops"
raiseAssert "implemented in the vmops"
proc contains*(t: CacheTable; key: string): bool {.inline.} =
## Alias of [hasKey][hasKey(CacheTable, string)] for use with the `in` operator.

View File

@@ -365,7 +365,7 @@ proc symBodyHash*(s: NimNode): string {.noSideEffect.} =
## and owning module, but also implementation body. All procs/variables used in
## the implementation of this symbol are hashed recursively as well, including
## magics from system module.
discard
raiseAssert "implemented in the vmops"
proc getTypeImpl*(n: typedesc): NimNode {.magic: "NGetType", noSideEffect.}
## Version of `getTypeImpl` which takes a `typedesc`.
@@ -1508,6 +1508,7 @@ proc expectIdent*(n: NimNode, name: string) {.since: (1,1).} =
proc hasArgOfName*(params: NimNode; name: string): bool =
## Search `nnkFormalParams` for an argument.
result = false
expectKind(params, nnkFormalParams)
for i in 1..<params.len:
for j in 0..<params[i].len-2:
@@ -1575,6 +1576,7 @@ proc extractTypeImpl(n: NimNode): NimNode =
else: error("Invalid node to retrieve type implementation of: " & $n.kind)
proc customPragmaNode(n: NimNode): NimNode =
result = nil
expectKind(n, {nnkSym, nnkDotExpr, nnkBracketExpr, nnkTypeOfExpr, nnkType, nnkCheckedFieldExpr})
let
typ = n.getTypeInst()
@@ -1730,7 +1732,7 @@ macro unpackVarargs*(callee: untyped; args: varargs[untyped]): untyped =
for i in 0 ..< args.len:
result.add args[i]
proc getProjectPath*(): string = discard
proc getProjectPath*(): string = raiseAssert "implemented in the vmops"
## Returns the path to the currently compiling project.
##
## This is not to be confused with `system.currentSourcePath <system.html#currentSourcePath.t>`_
@@ -1773,6 +1775,7 @@ proc getOffset*(arg: NimNode): int {.magic: "NSizeOf", noSideEffect.} =
proc isExported*(n: NimNode): bool {.noSideEffect.} =
## Returns whether the symbol is exported or not.
raiseAssert "implemented in the vmops"
proc extractDocCommentsAndRunnables*(n: NimNode): NimNode =
## returns a `nnkStmtList` containing the top-level doc comments and

View File

@@ -24,7 +24,7 @@ type
proc initRLock*(lock: var RLock) {.inline.} =
## Initializes the given lock.
when defined(posix):
var a: SysLockAttr
var a: SysLockAttr = default(SysLockAttr)
initSysLockAttr(a)
setSysLockType(a, SysLockType_Reentrant)
initSysLock(lock, a.addr)

View File

@@ -145,7 +145,7 @@ proc getDiscriminant(aa: pointer, n: ptr TNimNode): int =
of 2: d = int(cast[ptr uint16](a +% n.offset)[])
of 4: d = int(cast[ptr uint32](a +% n.offset)[])
of 8: d = int(cast[ptr uint64](a +% n.offset)[])
else: assert(false)
else: raiseAssert "unreachable"
return d
proc selectBranch(aa: pointer, n: ptr TNimNode): ptr TNimNode =
@@ -158,7 +158,7 @@ proc selectBranch(aa: pointer, n: ptr TNimNode): ptr TNimNode =
result = n.sons[n.len]
proc newAny(value: pointer, rawType: PNimType): Any {.inline.} =
result.value = value
result = Any(value: value)
result.rawType = rawType
proc toAny*[T](x: var T): Any {.inline.} =
@@ -169,7 +169,7 @@ proc toAny*[T](x: var T): Any {.inline.} =
proc kind*(x: Any): AnyKind {.inline.} =
## Gets the type kind.
result = AnyKind(ord(x.rawType.kind))
result = cast[AnyKind](ord(x.rawType.kind))
proc size*(x: Any): int {.inline.} =
## Returns the size of `x`'s type.
@@ -178,12 +178,16 @@ proc size*(x: Any): int {.inline.} =
proc baseTypeKind*(x: Any): AnyKind {.inline.} =
## Gets the base type's kind. If `x` has no base type, `akNone` is returned.
if x.rawType.base != nil:
result = AnyKind(ord(x.rawType.base.kind))
result = cast[AnyKind](ord(x.rawType.base.kind))
else:
result = akNone
proc baseTypeSize*(x: Any): int {.inline.} =
## Returns the size of `x`'s base type. If `x` has no base type, 0 is returned.
if x.rawType.base != nil:
result = x.rawType.base.size
else:
result = 0
proc invokeNew*(x: Any) =
## Performs `new(x)`. `x` needs to represent a `ref`.
@@ -263,7 +267,7 @@ proc `[]`*(x: Any, i: int): Any =
if i >=% cast[PGenSeq](s).len:
raise newException(IndexDefect, formatErrorIndexBound(i, cast[PGenSeq](s).len-1))
return newAny(s +!! (align(GenericSeqSize, x.rawType.base.align)+i*bs), x.rawType.base)
else: assert false
else: raiseAssert "unreachable"
proc `[]=`*(x: Any, i: int, y: Any) =
## Accessor for an any `x` that represents an array or a sequence.
@@ -292,7 +296,7 @@ proc `[]=`*(x: Any, i: int, y: Any) =
raise newException(IndexDefect, formatErrorIndexBound(i, cast[PGenSeq](s).len-1))
assert y.rawType == x.rawType.base
genericAssign(s +!! (align(GenericSeqSize, x.rawType.base.align)+i*bs), y.value, y.rawType)
else: assert false
else: raiseAssert "unreachable"
proc len*(x: Any): int =
## `len` for an any `x` that represents an array or a sequence.
@@ -308,14 +312,13 @@ proc len*(x: Any): int =
result = 0
else:
result = pgenSeq.len
else: assert false
else: raiseAssert "unreachable"
proc base*(x: Any): Any =
## Returns the base type of `x` (useful for inherited object types).
result = Any(value: x.value)
result.rawType = x.rawType.base
result.value = x.value
proc isNil*(x: Any): bool =
## `isNil` for an `x` that represents a cstring, proc or
@@ -367,7 +370,7 @@ iterator fields*(x: Any): tuple[name: string, any: Any] =
# XXX BUG: does not work yet, however is questionable anyway
when false:
if x.rawType.kind == tyObject: t = cast[ptr PNimType](x.value)[]
var ret: seq[tuple[name: cstring, any: Any]]
var ret: seq[tuple[name: cstring, any: Any]] = @[]
if t.kind == tyObject:
while true:
fieldsAux(p, t.node, ret)
@@ -379,8 +382,9 @@ iterator fields*(x: Any): tuple[name: string, any: Any] =
yield ($name, any)
proc getFieldNode(p: pointer, n: ptr TNimNode, name: cstring): ptr TNimNode =
result = nil
case n.kind
of nkNone: assert(false)
of nkNone: raiseAssert "unreachable"
of nkSlot:
if cmpNimIdentifier(n.name, name) == 0:
result = n
@@ -418,7 +422,7 @@ proc `[]`*(x: Any, fieldName: string): Any =
assert x.rawType.kind in {tyTuple, tyObject}
let n = getFieldNode(x.value, t.node, fieldName)
if n != nil:
result.value = x.value +!! n.offset
result = Any(value: x.value +!! n.offset)
result.rawType = n.typ
elif x.rawType.kind == tyObject and x.rawType.base != nil:
return `[]`(newAny(x.value, x.rawType.base), fieldName)
@@ -428,7 +432,7 @@ proc `[]`*(x: Any, fieldName: string): Any =
proc `[]`*(x: Any): Any =
## Dereference operator for `Any`. `x` needs to represent a ptr or a ref.
assert x.rawType.kind in {tyRef, tyPtr}
result.value = cast[ppointer](x.value)[]
result = Any(value: cast[ppointer](x.value)[])
result.rawType = x.rawType.base
proc `[]=`*(x, y: Any) =
@@ -481,12 +485,12 @@ proc getBiggestInt*(x: Any): BiggestInt =
of 2: result = int64(cast[ptr uint16](x.value)[])
of 4: result = BiggestInt(cast[ptr int32](x.value)[])
of 8: result = BiggestInt(cast[ptr int64](x.value)[])
else: assert false
else: raiseAssert "unreachable"
of tyUInt: result = BiggestInt(cast[ptr uint](x.value)[])
of tyUInt8: result = BiggestInt(cast[ptr uint8](x.value)[])
of tyUInt16: result = BiggestInt(cast[ptr uint16](x.value)[])
of tyUInt32: result = BiggestInt(cast[ptr uint32](x.value)[])
else: assert false
else: raiseAssert "unreachable"
proc setBiggestInt*(x: Any, y: BiggestInt) =
## Sets the integer value of `x`. `x` needs to represent
@@ -548,7 +552,7 @@ proc getBiggestUint*(x: Any): uint64 =
of tyUInt16: result = uint64(cast[ptr uint16](x.value)[])
of tyUInt32: result = uint64(cast[ptr uint32](x.value)[])
of tyUInt64: result = uint64(cast[ptr uint64](x.value)[])
else: assert false
else: raiseAssert "unreachable"
proc setBiggestUint*(x: Any; y: uint64) =
## Sets the unsigned integer value of `x`. `x` needs to represent an
@@ -560,7 +564,7 @@ proc setBiggestUint*(x: Any; y: uint64) =
of tyUInt16: cast[ptr uint16](x.value)[] = uint16(y)
of tyUInt32: cast[ptr uint32](x.value)[] = uint32(y)
of tyUInt64: cast[ptr uint64](x.value)[] = uint64(y)
else: assert false
else: raiseAssert "unreachable"
proc getChar*(x: Any): char =
## Retrieves the `char` value out of `x`. `x` needs to represent a `char`.
@@ -577,8 +581,8 @@ proc getBool*(x: Any): bool =
proc skipRange*(x: Any): Any =
## Skips the range information of `x`.
assert x.rawType.kind == tyRange
result = Any(value: x.value)
result.rawType = x.rawType.base
result.value = x.value
proc getEnumOrdinal*(x: Any, name: string): int =
## Gets the enum field ordinal from `name`. `x` needs to represent an enum
@@ -640,7 +644,7 @@ proc getBiggestFloat*(x: Any): BiggestFloat =
of tyFloat: result = BiggestFloat(cast[ptr float](x.value)[])
of tyFloat32: result = BiggestFloat(cast[ptr float32](x.value)[])
of tyFloat64: result = BiggestFloat(cast[ptr float64](x.value)[])
else: assert false
else: raiseAssert "unreachable"
proc setBiggestFloat*(x: Any, y: BiggestFloat) =
## Sets the float value of `x`. `x` needs to represent
@@ -649,7 +653,7 @@ proc setBiggestFloat*(x: Any, y: BiggestFloat) =
of tyFloat: cast[ptr float](x.value)[] = y
of tyFloat32: cast[ptr float32](x.value)[] = y.float32
of tyFloat64: cast[ptr float64](x.value)[] = y
else: assert false
else: raiseAssert "unreachable"
proc getString*(x: Any): string =
## Retrieves the `string` value out of `x`. `x` needs to represent a `string`.
@@ -682,7 +686,7 @@ iterator elements*(x: Any): int =
let typ = x.rawType
let p = x.value
# "typ.slots.len" field is for sets the "first" field
var u: int64
var u: int64 = 0'i64
case typ.size
of 1: u = int64(cast[ptr uint8](p)[])
of 2: u = int64(cast[ptr uint16](p)[])

View File

@@ -82,7 +82,7 @@ proc diffCodes(aText: string; h: var Table[string, int]): DiffData =
## `trimSpace` ignore leading and trailing space characters
## Returns a array of integers.
var lastUsedCode = h.len
result.data = newSeq[int]()
result = DiffData(data: newSeq[int]())
for s in aText.splitLines:
if h.contains s:
result.data.add h[s]
@@ -123,7 +123,7 @@ proc sms(dataA: var DiffData; lowerA, upperA: int; dataB: DiffData; lowerB, uppe
## `downVector` a vector for the (0,0) to (x,y) search. Passed as a parameter for speed reasons.
## `upVector` a vector for the (u,v) to (N,M) search. Passed as a parameter for speed reasons.
## Returns a MiddleSnakeData record containing x,y and u,v.
result = Smsrd()
let max = dataA.len + dataB.len + 1
let downK = lowerA - lowerB # the k-line to start the forward search
@@ -250,6 +250,7 @@ proc lcs(dataA: var DiffData; lowerA, upperA: int; dataB: var DiffData; lowerB,
proc createDiffs(dataA, dataB: DiffData): seq[Item] =
## Scan the tables of which lines are inserted and deleted,
## producing an edit script in forward order.
result = @[]
var startA = 0
var startB = 0
var lineA = 0

View File

@@ -146,6 +146,7 @@ proc respondError(req: Request, code: HttpCode): Future[void] =
result = req.client.send(msg)
proc parseProtocol(protocol: string): tuple[orig: string, major, minor: int] =
result = default(tuple[orig: string, major, minor: int])
var i = protocol.skipIgnoreCase("HTTP/")
if i != 5:
raise newException(ValueError, "Invalid request protocol. Got: " &

View File

@@ -187,7 +187,7 @@ proc encodeMime*(s: string, lineLen = 75.Positive, newLine = "\r\n",
if e.len <= lineLen or newLine.len == 0:
return e
result = newString(e.len + newLine.len * ((e.len div lineLen) - int(e.len mod lineLen == 0)))
var i, j, k, b: int
var i, j, k, b: int = 0
let nd = e.len - lineLen
while j < nd:
cpy(i + lineLen, e, j)
@@ -197,6 +197,7 @@ proc encodeMime*(s: string, lineLen = 75.Positive, newLine = "\r\n",
proc initDecodeTable*(): array[256, char] =
# computes a decode table at compile time
result = default(array[256, char])
for i in 0 ..< 256:
let ch = char(i)
var code = invalidChar
@@ -219,6 +220,7 @@ proc decode*(s: string): string =
runnableExamples:
assert decode("SGVsbG8gV29ybGQ=") == "Hello World"
assert decode(" SGVsbG8gV29ybGQ=") == "Hello World"
result = ""
if s.len == 0: return
proc decodeSize(size: int): int =

View File

@@ -83,6 +83,8 @@ proc getEncodedData(allowedMethods: set[RequestMethod]): string =
else:
if methodNone notin allowedMethods:
cgiError("'REQUEST_METHOD' must be 'POST' or 'GET'")
else:
result = ""
iterator decodeData*(data: string): tuple[key, value: string] =
## Reads and decodes CGI data and yields the (name, value) pairs the

View File

@@ -533,5 +533,5 @@ proc toCritBitTree*(items: sink openArray[string]): CritBitTree[void] {.since: (
## Creates a new `CritBitTree` that contains the given `items`.
runnableExamples:
doAssert ["a", "b", "c"].toCritBitTree is CritBitTree[void]
result = default(CritBitTree[void])
for item in items: result.incl item

View File

@@ -91,7 +91,7 @@ proc extractRGB*(a: Color): tuple[r, g, b: range[0..255]] =
echo typeof(extractRGB(a))
echo extractRGB(b)
echo typeof(extractRGB(b))
result = default(tuple[r, g, b: range[0..255]])
result.r = a.int shr 16 and 0xff
result.g = a.int shr 8 and 0xff
result.b = a.int and 0xff

View File

@@ -65,10 +65,10 @@ proc advice*(s: var ThreadPoolState): ThreadPoolAdvice =
proc fscanf(c: File, frmt: cstring) {.varargs, importc,
header: "<stdio.h>".}
var f: File
var f: File = default(File)
if f.open("/proc/loadavg"):
var b: float
var busy, total: int
var busy, total: int = 0
fscanf(f,"%lf %lf %lf %ld/%ld",
addr b, addr b, addr b, addr busy, addr total)
f.close()

View File

@@ -155,6 +155,8 @@ proc selectWorker(w: ptr Worker; fn: WorkerProc; data: pointer): bool =
signal(w.taskArrived)
blockUntil(w.taskStarted)
result = true
else:
result = false
proc cleanFlowVars(w: ptr Worker) =
let q = addr(w.q)
@@ -277,7 +279,7 @@ proc blockUntilAny*(flowVars: openArray[FlowVarBase]): int =
## to be able to wait on, -1 is returned.
##
## **Note:** This results in non-deterministic behaviour and should be avoided.
var ai: AwaitInfo
var ai: AwaitInfo = AwaitInfo()
ai.cv.initSemaphore()
var conflicts = 0
result = -1

View File

@@ -39,6 +39,7 @@ func startsWith*(s, prefix: cstring): bool {.rtl, extern: "csuStartsWith".} =
when defined(js):
result = jsStartsWith(s, prefix)
else:
result = false
var i = 0
while true:
if prefix[i] == '\0': return true
@@ -60,6 +61,7 @@ func endsWith*(s, suffix: cstring): bool {.rtl, extern: "csuEndsWith".} =
when defined(js):
result = jsEndsWith(s, suffix)
else:
result = false
let slen = s.len
var i = 0
var j = slen - len(suffix)

View File

@@ -90,6 +90,7 @@ proc loadLibPattern*(pattern: string, globalSymbols = false): LibHandle =
## pragma does. Returns nil if the library could not be loaded.
##
## .. warning:: this proc uses the GC and so cannot be used to load the GC.
result = default(LibHandle)
var candidates = newSeq[string]()
libCandidates(pattern, candidates)
for c in candidates:

View File

@@ -464,7 +464,7 @@ else:
var outLen = csize_t len(result)
var src = cstring(s)
var dst = cstring(result)
var iconvres: csize_t
var iconvres: csize_t = csize_t(0)
while inLen > 0:
iconvres = iconv(c, addr src, addr inLen, addr dst, addr outLen)
if iconvres == high(csize_t):

View File

@@ -55,7 +55,7 @@ when useBuiltinSwap:
## We have to use `copyMem` here instead of a simple dereference because they
## may point to a unaligned address. A sufficiently smart compiler _should_
## be able to elide them when they're not necessary.
var tmp: T
var tmp: T = default(T)
copyMem(addr tmp, inp, sizeof(T))
tmp = op(tmp)
copyMem(outp, addr tmp, sizeof(T))

View File

@@ -122,6 +122,7 @@ proc hiXorLo(a, b: uint64): uint64 {.inline.} =
when Hash.sizeof < 8:
result = hiXorLoFallback64(a, b)
elif defined(gcc) or defined(llvm_gcc) or defined(clang):
result = uint64(0)
{.emit: """__uint128_t r = `a`; r *= `b`; `result` = (r >> 64) ^ r;""".}
elif defined(windows) and not defined(tcc):
proc umul128(a, b: uint64, c: ptr uint64): uint64 {.importc: "_umul128", header: "intrin.h".}
@@ -316,7 +317,7 @@ proc murmurHash(x: openArray[byte]): Hash =
stepSize = 4 # 32-bit
n = size div stepSize
var
h1: uint32
h1: uint32 = uint32(0)
i = 0
@@ -328,7 +329,7 @@ proc murmurHash(x: openArray[byte]): Hash =
# body
while i < n * stepSize:
var k1: uint32
var k1: uint32 = uint32(0)
when nimvm:
impl()
@@ -348,7 +349,7 @@ proc murmurHash(x: openArray[byte]): Hash =
h1 = h1*5 + n1
# tail
var k1: uint32
var k1: uint32 = uint32(0)
var rem = size mod stepSize
while rem > 0:
dec rem
@@ -396,13 +397,17 @@ proc load8e(s: openArray[byte], o=0): uint64 {.inline.} =
proc load4(s: openArray[byte], o=0): uint32 {.inline.} =
when nimvm: result = load4e(s, o)
else:
when declared copyMem: copyMem result.addr, s[o].addr, result.sizeof
when declared copyMem:
result = uint32(0)
copyMem result.addr, s[o].addr, result.sizeof
else: result = load4e(s, o)
proc load8(s: openArray[byte], o=0): uint64 {.inline.} =
when nimvm: result = load8e(s, o)
else:
when declared copyMem: copyMem result.addr, s[o].addr, result.sizeof
when declared copyMem:
result = uint64(0)
copyMem result.addr, s[o].addr, result.sizeof
else: result = load8e(s, o)
proc lenU(s: openArray[byte]): uint64 {.inline.} = s.len.uint64
@@ -488,9 +493,9 @@ proc hashFarm(s: openArray[byte]): uint64 {.inline.} =
x = seed
y = seed*k1 + 113
z = shiftMix(y*k2 + 113)*k2
v, w: Pair
v, w: Pair = default(Pair)
x = x*k2 + load8(s)
let eos = ((s.len - 1) div 64)*64
let eos = ((s.len - 1) div 64)*64
let last64 = eos + ((s.len - 1) and 63) - 63
while true:
x = rotR(x + y + v[0] + load8(s, o+8), 37)*k1

View File

@@ -74,6 +74,8 @@ proc delete[T](s: var seq[T], attr: T): bool =
s[idx] = s[L-1]
setLen(s, L-1)
result = true
else:
result = false
proc xmlCheckedTag*(argsList: NimNode, tag: string, optAttr = "", reqAttr = "",
isLeaf = false): NimNode =

View File

@@ -403,6 +403,7 @@ proc `$`*(data: MultipartData): string {.since: (1, 1).} =
## convert MultipartData to string so it's human readable when echo
## see https://github.com/nim-lang/Nim/issues/11863
const sep = "-".repeat(30)
result = ""
for pos, entry in data.content:
result.add(sep & center($pos, 3) & sep)
result.add("\nname=\"" & entry.name & "\"")
@@ -476,7 +477,7 @@ proc addFiles*(p: MultipartData, xs: openArray[tuple[name, file: string]],
## data.addFiles({"uploaded_file": "public/test.html"})
## ```
for name, file in xs.items:
var contentType: string
var contentType: string = ""
let (_, fName, ext) = splitFile(file)
if ext.len > 0:
contentType = mimeDb.getMimetype(ext[1..ext.high], "")
@@ -1039,7 +1040,7 @@ proc format(client: HttpClient | AsyncHttpClient,
await client.readFileSizes(multipart)
var length: int64
var length: int64 = int64(0)
for entry in multipart.content:
result.add(format(entry, bound) & httpNewLine)
if entry.isFile:
@@ -1082,7 +1083,7 @@ proc requestAux(client: HttpClient | AsyncHttpClient, url: Uri,
var newHeaders: HttpHeaders
var data: seq[string]
var data: seq[string] = @[]
if multipart != nil and multipart.content.len > 0:
# `format` modifies `client.headers`, see
# https://github.com/nim-lang/Nim/pull/18208#discussion_r647036979
@@ -1105,7 +1106,7 @@ proc requestAux(client: HttpClient | AsyncHttpClient, url: Uri,
await client.socket.send(headerString)
if data.len > 0:
var buffer: string
var buffer: string = ""
for i, entry in multipart.content:
buffer.add data[i]
if not entry.isFile: continue

View File

@@ -212,6 +212,7 @@ iterator pairs*(headers: HttpHeaders): tuple[key, value: string] =
func contains*(values: HttpHeaderValues, value: string): bool =
## Determines if `value` is one of the values inside `values`. Comparison
## is performed without case sensitivity.
result = false
for val in seq[string](values):
if val.toLowerAscii == value.toLowerAscii: return true
@@ -230,6 +231,7 @@ func getOrDefault*(headers: HttpHeaders, key: string,
func len*(headers: HttpHeaders): int {.inline.} = headers.table.len
func parseList(line: string, list: var seq[string], start: int): int =
result = 0
var i = 0
var current = ""
while start+i < line.len and line[start + i] notin {'\c', '\l'}:
@@ -244,7 +246,7 @@ func parseHeader*(line: string): tuple[key: string, value: seq[string]] =
##
## Used by `asynchttpserver` and `httpclient` internally and should not
## be used by you.
result.value = @[]
result = ("", @[])
var i = 0
i = line.parseUntil(result.key, ':')
inc(i) # skip :

View File

@@ -501,6 +501,7 @@ proc hash*(n: JsonNode): Hash {.noSideEffect.} =
result = Hash(0)
proc hash*(n: OrderedTable[string, JsonNode]): Hash =
result = default(Hash)
for key, val in n:
result = result xor (hash(key) !& hash(val))
result = !$result
@@ -512,7 +513,7 @@ proc len*(n: JsonNode): int =
case n.kind
of JArray: result = n.elems.len
of JObject: result = n.fields.len
else: discard
else: result = 0
proc `[]`*(node: JsonNode, name: string): JsonNode {.inline.} =
## Gets a field from a `JObject`, which must not be nil.
@@ -610,6 +611,8 @@ proc getOrDefault*(node: JsonNode, key: string): JsonNode =
## value at `key` does not exist, returns nil
if not isNil(node) and node.kind == JObject:
result = node.fields.getOrDefault(key)
else:
result = nil
proc `{}`*(node: JsonNode, key: string): JsonNode =
## Gets a field from a `node`. If `node` is nil or not an object or
@@ -937,7 +940,7 @@ iterator parseJsonFragments*(s: Stream, filename: string = ""; rawIntegers = fal
## field but kept as raw numbers via `JString`.
## If `rawFloats` is true, floating point literals will not be converted to a `JFloat`
## field but kept as raw numbers via `JString`.
var p: JsonParser
var p: JsonParser = default(JsonParser)
p.open(s, filename)
try:
discard getTok(p) # read first token
@@ -955,7 +958,7 @@ proc parseJson*(s: Stream, filename: string = ""; rawIntegers = false, rawFloats
## field but kept as raw numbers via `JString`.
## If `rawFloats` is true, floating point literals will not be converted to a `JFloat`
## field but kept as raw numbers via `JString`.
var p: JsonParser
var p: JsonParser = default(JsonParser)
p.open(s, filename)
try:
discard getTok(p) # read first token

View File

@@ -539,6 +539,7 @@ when not defined(js):
# ------
proc countLogLines(logger: RollingFileLogger): int =
result = 0
let fp = open(logger.baseName, fmRead)
for line in fp.lines():
result.inc()

View File

@@ -273,7 +273,7 @@ proc loadAny(p: var JsonParser, a: Any, t: var Table[BiggestInt, pointer]) =
of akRange: loadAny(p, a.skipRange, t)
proc loadAny(s: Stream, a: Any, t: var Table[BiggestInt, pointer]) =
var p: JsonParser
var p: JsonParser = default(JsonParser)
open(p, s, "unknown file")
next(p)
loadAny(p, a, t)

View File

@@ -127,7 +127,7 @@ template memOrNot(withMem, withoutMem): untyped =
proc transform(buffer: openArray[uint8], state: var MD5State) =
var
myBlock: MD5Block
myBlock: MD5Block = default(MD5Block)
encode(myBlock, buffer)
var a = state[0]
var b = state[1]
@@ -225,8 +225,8 @@ proc toMD5*(s: string): MD5Digest =
## * `$ proc <#$,MD5Digest>`_ for converting MD5Digest to string
runnableExamples:
assert $toMD5("abc") == "900150983cd24fb0d6963f7d28e17f72"
var c: MD5Context
result = default(MD5Digest)
var c: MD5Context = default(MD5Context)
md5Init(c)
md5Update(c, s.slice(0, s.len - 1))
md5Final(c, result)
@@ -248,8 +248,8 @@ proc getMD5*(s: string): string =
assert getMD5("abc") == "900150983cd24fb0d6963f7d28e17f72"
var
c: MD5Context
d: MD5Digest
c: MD5Context = default(MD5Context)
d: MD5Digest = default(MD5Digest)
md5Init(c)
md5Update(c, s.slice(0, s.len - 1))
md5Final(c, d)
@@ -319,7 +319,7 @@ proc md5Final*(c: var MD5Context, digest: var MD5Digest) =
## If you use the `toMD5 proc <#toMD5,string>`_, there's no need to call this
## function explicitly.
var
Bits: MD5CBits
Bits: MD5CBits = default(MD5CBits)
PadLen: int
decode(Bits, c.count)
var Index = int((c.count[0] shr 3) and 0x3F)

View File

@@ -52,7 +52,7 @@ proc setFileSize(fh: FileHandle, newFileSize = -1, oldSize = -1): OSErrorCode =
result = lastErr
else:
if newFileSize > oldSize: # grow the file
var e: cint # posix_fallocate truncates up when needed.
var e: cint = cint(0) # posix_fallocate truncates up when needed.
when declared(posix_fallocate):
while (e = posix_fallocate(fh, 0, newFileSize); e == EINTR):
discard
@@ -167,7 +167,7 @@ proc open*(filename: string, mode: FileMode = fmRead,
## # Read the first 512 bytes
## mm_half = memfiles.open("/tmp/test.mmap", mode = fmReadWrite, mappedSize = 512)
## ```
result = default(MemFile)
# The file can be resized only when write mode is used:
if mode == fmAppend:
raise newEIO("The append mode is not supported.")
@@ -271,7 +271,7 @@ proc open*(filename: string, mode: FileMode = fmRead,
if mappedSize != -1: # XXX Logic here differs from `when windows` branch ..
result.size = mappedSize # .. which always fstats&Uses min(mappedSize, st).
else: # if newFileSize!=-1: result.size=newFileSize # if trust setFileSize
var stat: Stat # ^^.. BUT some FSes (eg. Linux HugeTLBfs) round to 2MiB.
var stat: Stat = default(Stat) # ^^.. BUT some FSes (eg. Linux HugeTLBfs) round to 2MiB.
if fstat(result.handle, stat) != -1:
result.size = stat.st_size.int # int may be 32-bit-unsafe for 2..<4 GiB
else:

View File

@@ -1038,7 +1038,7 @@ func newMimetypes*(): MimeDB =
## Creates a new Mimetypes database. The database will contain the most
## common mimetypes.
{.cast(noSideEffect).}:
result.mimes = mimes.toOrderedTable()
result = MimeDB(mimes: mimes.toOrderedTable())
func getMimetype*(mimedb: MimeDB, ext: string, default = "text/plain"): string =
## Gets mimetype which corresponds to `ext`. Returns `default` if `ext`

View File

@@ -143,6 +143,7 @@ else:
# avoid calling 'getTicks' too frequently
proc requestedHook(): bool {.nimcall.} =
result = false
if interval == 0: result = true
elif gTicker == 0:
gTicker = 500
@@ -174,7 +175,7 @@ proc writeProfile() {.noconv.} =
system.profilerHook = nil
const filename = "profile_results.txt"
echo "writing " & filename & "..."
var f: File
var f: File = default(File)
if open(f, filename, fmWrite):
sort(profileData, cmpEntries)
writeLine(f, "total executions of each stack trace:")

View File

@@ -44,6 +44,7 @@ proc hexbyte*(hex: char): int {.inline.} =
proc parseOid*(str: cstring): Oid =
## Parses an OID.
result = Oid()
var bytes = cast[cstring](cast[pointer](cast[int](addr(result.time)) + 4))
var i = 0
while i < 12:
@@ -53,7 +54,7 @@ proc parseOid*(str: cstring): Oid =
proc `$`*(oid: Oid): string =
## Converts an OID to a string.
const hex = "0123456789abcdef"
result = ""
result.setLen 24
var o = oid
@@ -89,11 +90,12 @@ proc genOid*(): Oid =
doAssert ($genOid()).len == 24
runnableExamples("-r:off"):
echo $genOid() # for example, "5fc7f546ddbbc84800006aaf"
result = Oid()
genOid(result, incr, fuzz)
proc generatedTime*(oid: Oid): Time =
## Returns the generated timestamp of the OID.
var tmp: int64
var tmp: int64 = int64(0)
var dummy = oid.time
bigEndian64(addr(tmp), addr(dummy))
result = fromUnix(tmp)

View File

@@ -13,6 +13,9 @@
# Note: Only add new enum values at the end to ensure binary compatibility with
# other Nim compiler versions!
when defined(nimPreviewSlimSystem):
import std/assertions
type
SingleValueSetting* {.pure.} = enum ## \
## settings resulting in a single string value
@@ -54,6 +57,7 @@ proc querySetting*(setting: SingleValueSetting): string {.
##
runnableExamples:
const nimcache = querySetting(SingleValueSetting.nimcacheDir)
raiseAssert "implemented in the vmops"
proc querySettingSeq*(setting: MultipleValueSetting): seq[string] {.
compileTime, noSideEffect.} =
@@ -64,3 +68,4 @@ proc querySettingSeq*(setting: MultipleValueSetting): seq[string] {.
## * `compileOption <system.html#compileOption,string,string>`_ for enum options
runnableExamples:
const nimblePaths = querySettingSeq(MultipleValueSetting.nimblePaths)
raiseAssert "implemented in the vmops"

View File

@@ -114,7 +114,7 @@ proc editDistance*(a, b: string): int {.noSideEffect.} =
iCurrentA = iStart
var
char2pI = -1
char2pPrev: int
char2pPrev: int = 0
for i in 1 .. (len1 - 1):
iNextA = iCurrentA
a.fastRuneAt(iNextA, runeA)

View File

@@ -16,11 +16,14 @@
import std/macros
proc getRaisesListImpl(n: NimNode): NimNode = discard "see compiler/vmops.nim"
proc getTagsListImpl(n: NimNode): NimNode = discard "see compiler/vmops.nim"
proc getForbidsListImpl(n: NimNode): NimNode = discard "see compiler/vmops.nim"
proc isGcSafeImpl(n: NimNode): bool = discard "see compiler/vmops.nim"
proc hasNoSideEffectsImpl(n: NimNode): bool = discard "see compiler/vmops.nim"
when defined(nimPreviewSlimSystem):
import std/assertions
proc getRaisesListImpl(n: NimNode): NimNode = raiseAssert "see compiler/vmops.nim"
proc getTagsListImpl(n: NimNode): NimNode = raiseAssert "see compiler/vmops.nim"
proc getForbidsListImpl(n: NimNode): NimNode = raiseAssert "see compiler/vmops.nim"
proc isGcSafeImpl(n: NimNode): bool = raiseAssert "see compiler/vmops.nim"
proc hasNoSideEffectsImpl(n: NimNode): bool = raiseAssert "see compiler/vmops.nim"
proc getRaisesList*(fn: NimNode): NimNode =
## Extracts the `.raises` list of the func/proc/etc `fn`.

View File

@@ -11,6 +11,9 @@
## The `std/envvars` module implements environment variable handling.
import std/oserrors
when defined(nimPreviewSlimSystem):
import std/assertions
type
ReadEnvEffect* = object of ReadIOEffect ## Effect that denotes a read
## from an environment variable.
@@ -200,7 +203,7 @@ when not defined(nimscript):
let p = find(kv, '=')
yield (substr(kv, 0, p-1), substr(kv, p+1))
proc envPairsImplSeq(): seq[tuple[key, value: string]] = discard # vmops
proc envPairsImplSeq(): seq[tuple[key, value: string]] = raiseAssert "implemented in the vmops" # vmops
iterator envPairs*(): tuple[key, value: string] {.tags: [ReadEnvEffect].} =
## Iterate over all `environments variables`:idx:.

View File

@@ -98,7 +98,7 @@ proc getMonoTime*(): MonoTime {.tags: [TimeEffect].} =
result = MonoTime(ticks: (ticks * 1_000_000_000).int64)
elif defined(macosx):
let ticks = mach_absolute_time()
var machAbsoluteTimeFreq: MachTimebaseInfoData
var machAbsoluteTimeFreq: MachTimebaseInfoData = default(MachTimebaseInfoData)
mach_timebase_info(machAbsoluteTimeFreq)
result = MonoTime(ticks: ticks * machAbsoluteTimeFreq.numer div
machAbsoluteTimeFreq.denom)
@@ -106,15 +106,15 @@ proc getMonoTime*(): MonoTime {.tags: [TimeEffect].} =
let ticks = k_ticks_to_ns_floor64(k_uptime_ticks())
result = MonoTime(ticks: ticks)
elif defined(posix):
var ts: Timespec
var ts: Timespec = default(Timespec)
discard clock_gettime(CLOCK_MONOTONIC, ts)
result = MonoTime(ticks: ts.tv_sec.int64 * 1_000_000_000 +
ts.tv_nsec.int64)
elif defined(windows):
var ticks: uint64
var ticks: uint64 = 0'u64
QueryPerformanceCounter(ticks)
var freq: uint64
var freq: uint64 = 0'u64
QueryPerformanceFrequency(freq)
let queryPerformanceCounterFreq = 1_000_000_000'u64 div freq
result = MonoTime(ticks: (ticks * queryPerformanceCounterFreq).int64)

View File

@@ -88,6 +88,7 @@ proc rsGetPosition(s: Stream): int =
return s.pos
proc rsPeekData(s: Stream, buffer: pointer, bufLen: int): int =
result = 0
let s = ReadSocketStream(s)
if bufLen > 0:
let oldLen = s.buf.len

View File

@@ -1,13 +1,16 @@
## This module implements path handling like os module but works at only compile-time.
## This module works even when cross compiling to OS that is not supported by os module.
when defined(nimPreviewSlimSystem):
import std/assertions
proc staticFileExists*(filename: string): bool {.compileTime.} =
## Returns true if `filename` exists and is a regular file or symlink.
##
## Directories, device files, named pipes and sockets return false.
discard
raiseAssert "implemented in the vmops"
proc staticDirExists*(dir: string): bool {.compileTime.} =
## Returns true if the directory `dir` exists. If `dir` is a file, false
## is returned. Follows symlinks.
discard
raiseAssert "implemented in the vmops"

View File

@@ -287,6 +287,7 @@ else:
discard posix.close(fd)
proc urandomInternalImpl(dest: var openArray[byte]): int {.inline.} =
result = 0
when batchImplOS:
batchImpl(result, dest, getRandomImpl)
else:

View File

@@ -156,6 +156,7 @@ proc createTempFile*(prefix, suffix: string, dir = ""): tuple[cfile: File, path:
assert readFile(path) == "foo"
removeFile(path)
# xxx why does above work without `cfile.flushFile` ?
result = default(tuple[cfile: File, path: string])
let dir = getTempDirImpl(dir)
for i in 0 ..< maxRetry:
result.path = genTempPath(prefix, suffix, dir)

View File

@@ -107,10 +107,10 @@ proc writeVu64*(z: var openArray[byte], x: uint64): int =
varintWrite32(toOpenArray(z, 5, 8), y)
return 9
proc sar(a, b: int64): int64 =
proc sar(a, b: int64): int64 {.noinit.} =
{.emit: [result, " = ", a, " >> ", b, ";"].}
proc sal(a, b: int64): int64 =
proc sal(a, b: int64): int64 {.noinit.} =
{.emit: [result, " = ", a, " << ", b, ";"].}
proc encodeZigzag*(x: int64): uint64 {.inline.} =

View File

@@ -61,10 +61,11 @@ proc finalize(n: NimNode, lhs: NimNode, level: int): NimNode =
result = quote: (let `lhs` = `n`)
proc process(n: NimNode, lhs: NimNode, label: NimNode, level: int): NimNode =
result = nil
var n = n.copyNimTree
var it = n
let addr2 = bindSym"addr"
var old: tuple[n: NimNode, index: int]
var old: tuple[n: NimNode, index: int] = (nil, 0)
while true:
if it.len == 0:
result = finalize(n, lhs, level)

View File

@@ -405,6 +405,7 @@ proc recv*[TMsg](c: var Channel[TMsg]): TMsg =
##
## This blocks until a message has arrived!
## You may use `peek proc <#peek,Channel[TMsg]>`_ to avoid the blocking.
result = default(TMsg)
var q = cast[PRawChannel](addr(c))
acquireSys(q.lock)
llRecv(q, addr(result), cast[PNimType](getTypeInfo(result)))
@@ -417,6 +418,7 @@ proc tryRecv*[TMsg](c: var Channel[TMsg]): tuple[dataAvailable: bool,
##
## If it fails, it returns `(false, default(msg))` otherwise it
## returns `(true, msg)`.
result = default(tuple[dataAvailable: bool, msg: TMsg])
var q = cast[PRawChannel](addr(c))
if q.mask != ChannelDeadMask:
if tryAcquireSys(q.lock):

View File

@@ -192,6 +192,7 @@ proc listEpc(): SexpNode =
proc findNode(n: PNode; trackPos: TLineInfo): PSym =
#echo "checking node ", n.info
result = nil
if n.kind == nkSym:
if isTracked(n.info, trackPos, n.sym.name.s.len): return n.sym
else:
@@ -203,6 +204,8 @@ proc symFromInfo(graph: ModuleGraph; trackPos: TLineInfo): PSym =
let m = graph.getModule(trackPos.fileIndex)
if m != nil and m.ast != nil:
result = findNode(m.ast, trackPos)
else:
result = nil
template benchmark(benchmarkName: untyped, code: untyped) =
block:
@@ -411,7 +414,7 @@ proc replTcp(x: ThreadParams) {.thread.} =
server.bindAddr(x.port, x.address)
server.listen()
var inp = ""
var stdoutSocket: Socket
var stdoutSocket: Socket = Socket()
while true:
accept(server, stdoutSocket)
@@ -445,7 +448,7 @@ proc replEpc(x: ThreadParams) {.thread.} =
echo port
stdout.flushFile()
var client: Socket
var client: Socket = Socket()
# Wait for connection
accept(server, client)
while true:
@@ -849,6 +852,7 @@ func deduplicateSymInfoPair(xs: SuggestFileSymbolDatabase): SuggestFileSymbolDat
proc findSymData(graph: ModuleGraph, trackPos: TLineInfo):
ref SymInfoPair =
result = nil
let db = graph.fileSymbols(trackPos.fileIndex).deduplicateSymInfoPair
doAssert(db.fileIndex == trackPos.fileIndex)
for i in db.lineInfo.low..db.lineInfo.high:
@@ -983,6 +987,7 @@ proc symbolEqual(left, right: PSym): bool =
return left.info.exactEquals(right.info) and left.name == right.name
proc findDef(n: PNode, line: uint16, col: int16): PNode =
result = nil
if n.kind in {nkProcDef, nkIteratorDef, nkTemplateDef, nkMethodDef, nkMacroDef}:
if n.info.line == line:
return n
@@ -1003,6 +1008,8 @@ proc findByTLineInfo(trackPos: TLineInfo, infoPairs: SuggestFileSymbolDatabase):
break
proc outlineNode(graph: ModuleGraph, n: PNode, endInfo: TLineInfo, infoPairs: SuggestFileSymbolDatabase): bool =
result = false
proc checkSymbol(sym: PSym, info: TLineInfo): bool =
result = (sym.owner.kind in {skModule, skType} or sym.kind in {skProc, skMethod, skIterator, skTemplate, skType})
@@ -1017,6 +1024,7 @@ proc outlineNode(graph: ModuleGraph, n: PNode, endInfo: TLineInfo, infoPairs: Su
return true
proc handleIdentOrSym(graph: ModuleGraph, n: PNode, endInfo: TLineInfo, infoPairs: SuggestFileSymbolDatabase): bool =
result = false
for child in n:
if child.kind in {nkIdent, nkSym}:
if graph.outlineNode(child, endInfo, infoPairs):
@@ -1067,7 +1075,7 @@ proc executeNoHooksV3(cmd: IdeCmd, file: AbsoluteFile, dirtyfile: AbsoluteFile,
myLog fmt "cmd: {cmd}, file: {file}[{line}:{col}], dirtyFile: {dirtyfile}, tag: {tag}"
var fileIndex: FileIndex
var fileIndex: FileIndex = default(FileIndex)
if not (cmd in {ideRecompile, ideGlobalSymbols}):
fileIndex = fileInfoIdx(conf, file)
@@ -1197,7 +1205,7 @@ proc executeNoHooksV3(cmd: IdeCmd, file: AbsoluteFile, dirtyfile: AbsoluteFile,
if not s.isNil:
# find first mention of the symbol in the file containing the definition.
# It is either the definition or the declaration.
var first: SymInfoPair
var first: SymInfoPair = default(SymInfoPair)
let db = graph.fileSymbols(s.sym.info.fileIndex).deduplicateSymInfoPair
for i in db.lineInfo.low..db.lineInfo.high:
if s.sym.symbolEqual(db.sym[i]):
@@ -1256,7 +1264,7 @@ proc executeNoHooksV3(cmd: IdeCmd, file: AbsoluteFile, dirtyfile: AbsoluteFile,
var typeHints = true
var exceptionHints = false
while i <= tag.high:
var token: string
var token: string = ""
i += parseUntil(tag, token, seps, i)
i += skipWhile(tag, seps, i)
case token:

View File

@@ -22,3 +22,6 @@ define:nimcore
#define:noDocgen
--path:"$nim"
--threads:on
--warningAserror:ProveInit
--warningAserror:Uninit

View File

@@ -152,7 +152,7 @@ proc parseString(my: var SexpParser): TTokKind =
inc(pos, 2)
of 'u':
inc(pos, 2)
var r: int
var r: int = 0
if handleHexChar(my.buf[pos], r): inc(pos)
if handleHexChar(my.buf[pos], r): inc(pos)
if handleHexChar(my.buf[pos], r): inc(pos)
@@ -452,7 +452,7 @@ proc len*(n: SexpNode): int =
## Else it returns 0.
case n.kind
of SList: result = n.elems.len
else: discard
else: result = 0
proc `[]`*(node: SexpNode, index: int): SexpNode =
## Gets the node at `index` in a List. Result is undefined if `index`
@@ -629,7 +629,7 @@ proc open*(my: var SexpParser, input: Stream) =
proc parseSexp*(s: Stream): SexpNode =
## Parses from a buffer `s` into a `SexpNode`.
var p: SexpParser
var p: SexpParser = SexpParser()
p.open(s)
discard getTok(p) # read first token
result = p.parseSexp()

View File

@@ -37,8 +37,7 @@ proc exe*(f: string): string =
proc findNimImpl*(): tuple[path: string, ok: bool] =
if nimExe.len > 0: return (nimExe, true)
let nim = "nim".exe
result.path = "bin" / nim
result.ok = true
result = ("bin" / nim, true)
if fileExists(result.path): return
for dir in split(getEnv("PATH"), PathSep):
result.path = dir / nim
@@ -98,6 +97,7 @@ pkgs/atlas/doc/atlas.md
""".splitWhitespace()
proc getMd2html(): seq[string] =
result = @[]
for a in walkDirRecFilter("doc"):
let path = a.path
if a.kind == pcFile and path.splitFile.ext == ".md" and path.lastPathPart notin
@@ -191,7 +191,8 @@ when (NimMajor, NimMinor) < (1, 1) or not declared(isRelativeTo):
proc getDocList(): seq[string] =
##
var docIgnore: HashSet[string]
result = @[]
var docIgnore: HashSet[string] = initHashSet[string]()
for a in withoutIndex: docIgnore.incl a
for a in ignoredModules: docIgnore.incl a
@@ -327,7 +328,7 @@ proc nim2pdf(src: string, dst: string, nimArgs: string) =
proc buildPdfDoc*(args: string, destPath: string) =
let args = nimArgs & " " & args
var pdfList: seq[string]
var pdfList: seq[string] = @[]
createDir(destPath)
if os.execShellCmd("xelatex -version") != 0:
doAssert false, "xelatex not found" # or, raise an exception