fixes strictdefs warnings continue (#24520)

(cherry picked from commit d2d810585c)
This commit is contained in:
ringabout
2024-12-13 22:04:49 +08:00
committed by narimiran
parent 1299dd4651
commit 5a71c36d25
49 changed files with 152 additions and 91 deletions

View File

@@ -1659,7 +1659,7 @@ proc trackProc*(c: PContext; s: PSym, body: PNode) =
(t.config.selectedGC in {gcArc, gcOrc, gcAtomicArc} and
(isClosure(typ.skipTypes(abstractInst)) or param.id in t.escapingParams)):
createTypeBoundOps(t, typ, param.info)
if isOutParam(typ) and param.id notin t.init:
if isOutParam(typ) and param.id notin t.init and s.magic == mNone:
message(g.config, param.info, warnProveInit, param.name.s)
if not isEmptyType(s.typ.returnType) and

View File

@@ -2688,7 +2688,7 @@ proc locals*(): RootObj {.magic: "Plugin", noSideEffect.} =
when hasAlloc and notJSnotNims:
# XXX how to implement 'deepCopy' is an open problem.
proc deepCopy*[T](x: var T, y: T) {.noSideEffect, magic: "DeepCopy".} =
proc deepCopy*[T](x: out T, y: T) {.noSideEffect, magic: "DeepCopy".} =
## Performs a deep copy of `y` and copies it into `x`.
##
## This is also used by the code generator

View File

@@ -73,30 +73,35 @@ proc chckIndx(i, a, b: int): int =
if i >= a and i <= b:
return i
else:
result = 0
raiseIndexError3(i, a, b)
proc chckRange(i, a, b: int): int =
if i >= a and i <= b:
return i
else:
result = 0
raiseRangeError(i)
proc chckRange64(i, a, b: int64): int64 {.compilerproc.} =
if i >= a and i <= b:
return i
else:
result = 0
raiseRangeError(i)
proc chckRangeU(i, a, b: uint64): uint64 {.compilerproc.} =
if i >= a and i <= b:
return i
else:
result = 0
sysFatal(RangeDefect, "value out of range")
proc chckRangeF(x, a, b: float): float =
if x >= a and x <= b:
return x
else:
result = 0.0
when hostOS == "standalone":
sysFatal(RangeDefect, "value out of range")
else:

View File

@@ -203,7 +203,7 @@ proc staticExec*(command: string, input = "", cache = ""): string {.
## ```
proc gorgeEx*(command: string, input = "", cache = ""): tuple[output: string,
exitCode: int] =
exitCode: int] {.noinit.} =
## Similar to `gorge <#gorge,string,string,string>`_ but also returns the
## precious exit code.
discard

View File

@@ -140,6 +140,8 @@ proc repr*[T: tuple|object](x: T): string {.noSideEffect, raises: [].} =
## ```
when T is object:
result = $typeof(x)
else:
result = ""
reprObject(result, x)
proc repr*[T](x: ref T | ptr T): string {.noSideEffect, raises: [].} =

View File

@@ -347,7 +347,7 @@ proc compileExample(r: var TResults, pattern, options: string, cat: Category) =
testSpec r, test
proc testStdlib(r: var TResults, pattern, options: string, cat: Category) =
var files: seq[string]
var files: seq[string] = @[]
proc isValid(file: string): bool =
for dir in parentDirs(file, inclusive = false):
@@ -383,11 +383,13 @@ proc testStdlib(r: var TResults, pattern, options: string, cat: Category) =
# ----------------------------- nimble ----------------------------------------
proc listPackagesAll(): seq[NimblePackage] =
result = @[]
var nimbleDir = getEnv("NIMBLE_DIR")
if nimbleDir.len == 0: nimbleDir = getHomeDir() / ".nimble"
let packageIndex = nimbleDir / "packages_official.json"
let packageList = parseFile(packageIndex)
proc findPackage(name: string): JsonNode =
result = nil
for a in packageList:
if a["name"].str == name: return a
for pkg in important_packages.packages.items:
@@ -411,17 +413,15 @@ proc listPackages(packageFilter: string): seq[NimblePackage] =
elif testamentData0.testamentNumBatch == 0:
result = pkgs
else:
result = @[]
let pkgs2 = pkgs.filterIt(not it.allowFailure)
for i in 0..<pkgs2.len:
if i mod testamentData0.testamentNumBatch == testamentData0.testamentBatch:
result.add pkgs2[i]
proc makeSupTest(test, options: string, cat: Category, debugInfo = ""): TTest =
result.cat = cat
result.name = test
result.options = options
result.debugInfo = debugInfo
result.startTime = epochTime()
result = TTest(cat: cat, name: test, options: options, debugInfo: debugInfo,
startTime: epochTime())
import std/private/gitutils
@@ -440,7 +440,7 @@ proc testNimblePackages(r: var TResults; cat: Category; packageFilter: string) =
var test = makeSupTest(pkg.name, "", cat, "[$#/$#] " % [$i, $pkgs.len])
let buildPath = packagesDir / pkg.name
template tryCommand(cmd: string, workingDir2 = buildPath, reFailed = reInstallFailed, maxRetries = 1): string =
var outp: string
var outp: string = ""
let ok = retryCall(maxRetry = maxRetries, backoffDuration = 10.0):
var status: int
(outp, status) = execCmdEx(cmd, workingDir = workingDir2)
@@ -583,7 +583,8 @@ proc isJoinableSpec(spec: TSpec): bool =
result = false
proc quoted(a: string): string =
# todo: consider moving to system.nim
# TODO: consider moving to system.nim
result = ""
result.addQuoted(a)
proc runJoinedTest(r: var TResults, cat: Category, testsDir: string, options: string) =
@@ -600,7 +601,7 @@ proc runJoinedTest(r: var TResults, cat: Category, testsDir: string, options: st
if kind == pcDir and cat notin specialCategories:
for file in walkDirRec(testsDir / cat):
if isTestFile(file):
var spec: TSpec
var spec: TSpec = default(TSpec)
try:
spec = parseSpec(file)
except ValueError:
@@ -621,7 +622,7 @@ proc runJoinedTest(r: var TResults, cat: Category, testsDir: string, options: st
echo s
return
var megatest: string
var megatest: string = ""
# xxx (minor) put outputExceptedFile, outputGottenFile, megatestFile under here or `buildDir`
var outDir = nimcacheDir(testsDir / "megatest", "", targetC)
template toMarker(file, i): string =
@@ -735,7 +736,7 @@ proc processCategory(r: var TResults, cat: Category,
runJoinedTest(r, cat, testsDir, options & " --mm:refc")
else:
var testsRun = 0
var files: seq[string]
var files: seq[string] = @[]
for file in walkDirRec(testsDir &.? cat.string):
if isTestFile(file): files.add file
files.sort # give reproducible order

View File

@@ -68,7 +68,7 @@ type
successPercentage, ignoredPercentage, failedPercentage: BiggestFloat
proc allTestResults(onlyFailing = false): AllTests =
result.data = newJArray()
result = AllTests(data: newJArray())
for file in os.walkFiles("testresults/*.json"):
let data = parseFile(file)
if data.kind != JArray:

View File

@@ -3,7 +3,7 @@ import std/[nativesockets, asyncdispatch, os]
proc bindAvailablePort*(handle: SocketHandle, port = Port(0)): Port =
## See also `asynchttpserver.getPort`.
block:
var name: Sockaddr_in
var name: Sockaddr_in = default(Sockaddr_in)
name.sin_family = typeof(name.sin_family)(toInt(AF_INET))
name.sin_port = htons(uint16(port))
name.sin_addr.s_addr = htonl(INADDR_ANY)

View File

@@ -299,6 +299,7 @@ proc extractSpec(filename: string; spec: var TSpec): string =
result = ""
proc parseTargets*(value: string): set[TTarget] =
result = default(set[TTarget])
for v in value.normalize.splitWhitespace:
case v
of "c": result.incl(targetC)
@@ -308,7 +309,7 @@ proc parseTargets*(value: string): set[TTarget] =
else: raise newException(ValueError, "invalid target: '$#'" % v)
proc initSpec*(filename: string): TSpec =
result.file = filename
result = TSpec(file: filename)
proc isCurrentBatch*(testamentData: TestamentData; filename: string): bool =
if testamentData.testamentNumBatch != 0:
@@ -317,13 +318,12 @@ proc isCurrentBatch*(testamentData: TestamentData; filename: string): bool =
true
proc parseSpec*(filename: string): TSpec =
result.file = filename
result.filename = extractFilename(filename)
result = TSpec(file: filename, filename: extractFilename(filename))
let specStr = extractSpec(filename, result)
var ss = newStringStream(specStr)
var p: CfgParser
var p: CfgParser = default(CfgParser)
open(p, ss, filename, 1)
var flags: HashSet[string]
var flags: HashSet[string] = initHashSet[string]()
var nimoutFound = false
while true:
var e = next(p)

View File

@@ -123,12 +123,12 @@ proc getFileDir(filename: string): string =
if not result.isAbsolute():
result = getCurrentDir() / result
proc execCmdEx2(command: string, args: openArray[string]; workingDir, input: string = ""): tuple[
proc execCmdEx2(command: string, args: openArray[string]; workingDir: string = "", input: string = ""): tuple[
cmdLine: string,
output: string,
exitCode: int] {.tags:
[ExecIOEffect, ReadIOEffect, RootEffect], gcsafe.} =
result = ("", "", 0)
result.cmdLine.add quoteShell(command)
for arg in args:
result.cmdLine.add ' '
@@ -173,8 +173,8 @@ proc prepareTestCmd(cmdTemplate, filename, options, nimcache: string,
proc callNimCompiler(cmdTemplate, filename, options, nimcache: string,
target: TTarget, extraOptions = ""): TSpec =
result.cmd = prepareTestCmd(cmdTemplate, filename, options, nimcache, target,
extraOptions)
result = TSpec(cmd: prepareTestCmd(cmdTemplate, filename, options, nimcache, target,
extraOptions))
verboseCmd(result.cmd)
var p = startProcess(command = result.cmd,
options = {poStdErrToStdOut, poUsePath, poEvalCommand})
@@ -229,11 +229,13 @@ proc callNimCompiler(cmdTemplate, filename, options, nimcache: string,
trimUnitSep result.msg
proc initResults: TResults =
result.total = 0
result.passed = 0
result.failedButAllowed = 0
result.skipped = 0
result.data = ""
result = TResults(
total: 0,
passed: 0,
failedButAllowed: 0,
skipped: 0,
data: ""
)
macro ignoreStyleEcho(args: varargs[typed]): untyped =
let typForegroundColor = bindSym"ForegroundColor".getType
@@ -370,7 +372,7 @@ proc finishTestRetryable(r: var TResults, test: TTest, target: TTarget,
addResult(r, test, target, extraOptions, expected, given, success, duration, allowFailure, givenSpec)
proc toString(inlineError: InlineError, filename: string): string =
result.add "$file($line, $col) $kind: $msg" % [
result = "$file($line, $col) $kind: $msg" % [
"file", filename,
"line", $inlineError.line,
"col", $inlineError.col,
@@ -379,6 +381,7 @@ proc toString(inlineError: InlineError, filename: string): string =
]
proc inlineErrorsMsgs(expected: TSpec): string =
result = ""
for inlineError in expected.inlineErrors.items:
result.addLine inlineError.toString(expected.filename)
@@ -622,17 +625,18 @@ proc testSpecWithNimcache(r: var TResults, test: TTest; nimcache: string) {.used
testSpecHelper(r, testClone, test.spec, target, "", nimcache)
proc makeTest(test, options: string, cat: Category): TTest =
result.cat = cat
result.name = test
result.options = options
result.spec = parseSpec(addFileExt(test, ".nim"))
result.startTime = epochTime()
result = TTest(
cat: cat,
name: test,
options: options,
spec: parseSpec(addFileExt(test, ".nim")),
startTime: epochTime()
)
proc makeRawTest(test, options: string, cat: Category): TTest {.used.} =
result.cat = cat
result.name = test
result.options = options
result.spec = initSpec(addFileExt(test, ".nim"))
result = TTest(cat: cat, name: test, options: options,
spec: initSpec(addFileExt(test, ".nim"))
)
result.spec.action = actionCompile
result.spec.targets = {getTestSpecTarget()}
result.startTime = epochTime()
@@ -668,6 +672,7 @@ else:
include categories
proc loadSkipFrom(name: string): seq[string] =
result = @[]
if name.len == 0: return
# One skip per line, comments start with #
# used by `nlvm` (at least)
@@ -769,7 +774,7 @@ proc main() =
if skipFrom.len > 0:
myself &= " " & quoteShell("--skipFrom:" & skipFrom)
var cats: seq[string]
var cats: seq[string] = @[]
let rest = if p.cmdLineRest.len > 0: " " & p.cmdLineRest else: ""
for kind, dir in walkDir(testsDir):
assert testsDir.startsWith(testsDir)
@@ -780,7 +785,7 @@ proc main() =
cats.add AdditionalCategories
if useMegatest: cats.add MegaTestCat
var cmds: seq[string]
var cmds: seq[string] = @[]
for cat in cats:
let runtype = if useMegatest: " pcat " else: " cat "
cmds.add(myself & runtype & quoteShell(cat) & rest)

View File

@@ -4,3 +4,5 @@ path = "$nim" # For compiler/nodejs
-d:ssl # For azure
# my SSL doesn't have this feature and I don't care:
-d:nimDisableCertificateValidation
--warningAserror:ProveInit
--warningAserror:Uninit

View File

@@ -31,10 +31,11 @@ type
se: seq[TA]
proc p(param1, param2: TC, param3: var TC): TC =
result = TC()
var
local: TC
plocal: ptr TC
plocal2: ptr TA
local: TC = default(TC)
plocal: ptr TC = nil
plocal2: ptr TA = nil
local.arr <| local
local.arr[0] <| local

View File

@@ -16,8 +16,9 @@ proc `$`*(a: MinValue): string {.inline.} =
result = "hello"
for i in a.symbols:
result = "hello"
else: discard
else: result = ""
proc parseMinValue*(): MinValue =
# or this echo
result = MinValue()
echo result

View File

@@ -1 +1,3 @@
--sinkInference:on
--warningAserror:ProveInit
--warningAserror:Uninit

View File

@@ -198,6 +198,7 @@ proc allocCpuStorage[T](s: var CpuStorage[T], size: int) =
s.size = size
proc newTensor[T](size: int): Tensor[T] =
result = default(Tensor[T])
allocCpuStorage(result.buf, size)
proc `[]`[T](t: Tensor[T], idx: int): T = t.buf.raw_buffer[idx]
@@ -209,7 +210,7 @@ proc toTensor[T](s: seq[T]): Tensor[T] =
result[i] = x
proc main2() =
var t: TestObject
var t: TestObject = TestObject()
t.x = toTensor(@[1.0, 2, 3, 4])
t.x = t.x
doAssert(t.x.buf != nil) # self-assignment above should be eliminated

View File

@@ -15,7 +15,8 @@ type
meshes*: seq[Mesh]
proc bork() : ImportedScene =
var mats: seq[ImportMaterial]
result = ImportedScene()
var mats: seq[ImportMaterial] = @[]
setLen(mats, 1)
add(result.meshes, Mesh(material: mats[0]))

View File

@@ -19,6 +19,7 @@ c_cursor = tmpTuple_cursor[2]
func fooLeaks(refTuple: tuple[a,
b,
c: seq[float]]): float =
result = 0.0
let (a, b, c) = refTuple
let refset = (a: newSeq[float](25_000_000),

View File

@@ -9,7 +9,7 @@ type NewString = object
proc len(s: NewString): int = 10
converter toNewString(x: WideCStringObj): NewString = discard
converter toNewString(x: WideCStringObj): NewString = default(NewString)
let w = newWideCString("test")
doAssert len(w) == 4

View File

@@ -41,6 +41,7 @@ proc pushScoped*[T](metric: string, blk: WithTimeCallback[T]): T {.gcsafe.} =
# demo code
discard pushScoped[int]("test.message") do (data: var JsonNode) -> int:
result = 0
data["test"] = %*{
"nested": "v1"
}

View File

@@ -5,14 +5,14 @@ discard """
import std/assertions
proc foo =
var s:seq[string]
var s:seq[string] = @[]
var res = ""
for i in 0..3:
s.add ("test" & $i)
s.add ("test" & $i)
var lastname:string
var lastname:string = ""
for i in s:
var name = i[0..4]

View File

@@ -40,6 +40,7 @@ proc `=sink`*[T](dest: var SharedPtr[T], src: SharedPtr[T]) =
proc newSharedPtr*[T](val: sink T): SharedPtr[T] =
result = default(SharedPtr[T])
result.val = cast[type(result.val)](alloc(sizeof(result.val[])))
reset(result.val[])
result.val.atomicCounter = 1

View File

@@ -26,7 +26,7 @@ proc `+.`[T](t1, t2: Tensor[T]): Tensor[T] =
proc toTensor*[T](a: sink seq[T]): Tensor[T] =
## This breaks it: Using `T` instead makes it work
type U = typeof(a[0])
var t: Tensor[U] # Tensor[T] works
var t: Tensor[U] = default(Tensor[U]) # Tensor[T] works
t.buf = a
result = t

View File

@@ -31,6 +31,7 @@ proc `+!`*(p: pointer, i: uint64): pointer {.inline.} =
proc charEq(x, c: char): bool {.inline.} = x == c
proc initSplitr*(delim: string): Splitr =
result = default(Splitr)
if delim == "white": #User can use any other permutation if needed
result.repeat = true
result.chrDlm = ' '
@@ -81,6 +82,7 @@ template defSplit[T](slc: T, fs: var seq[MemSlice], n: int, repeat: bool,
proc msplit*(s: MemSlice, fs: var seq[MemSlice], sep=' ', n=0,
repeat=false): int =
result = 0
defSplit(s, fs, n, repeat, sep, cmemchr, charEq)
proc split*(s: Splitr, line: MemSlice, cols: var seq[MemSlice],
@@ -92,6 +94,7 @@ proc split*(s: Splitr, line: MemSlice, cols: var seq[MemSlice],
# to mask the arc problem, as does simplifying `Table` to `seq[char]`.
proc load(path: string, delim=" "): Table[MemSlice, seq[char]] =
result = default(Table[MemSlice, seq[char]])
let f = memfiles.open(path)
let splitr = initSplitr(delim)
var cols: seq[MemSlice] = @[ ] # re-used seq buffer

View File

@@ -17,6 +17,7 @@ block:
private: PrivateKey
proc initKeyPair(): KeyPair =
result = KeyPair()
ed25519_create_keypair(result.public.addr, result.private.addr)
let keys = initKeyPair()
@@ -52,6 +53,7 @@ type Obj = tuple
arr: seq[int]
proc bug(): seq[Obj] =
result = @[]
result.add (value: 0, arr: @[])
result[^1].value = 1
result[^1].arr.add 1

View File

@@ -100,6 +100,7 @@ proc `=sink`*(m: var MyObj, m2: MyObj) =
m.data = m2.data
proc newMyObj(len: int): MyObj =
result = MyObj()
result.len = len
result.data = cast[ptr UncheckedArray[float]](allocShared(sizeof(float) * len))
@@ -117,6 +118,8 @@ proc takeSink(x: sink string): bool = true
proc b(x: sink string): string =
if takeSink(x):
return x & "abc"
else:
result = ""
proc bbb(inp: string) =
let y = inp & "xyz"
@@ -267,11 +270,11 @@ type
x: string
proc bug14495 =
var owners: seq[Gah]
var owners: seq[Gah] = @[]
for i in 0..10:
owners.add Gah(x: $i)
var x: seq[Gah]
var x: seq[Gah] = @[]
for i in 0..10:
x.add owners[i]
@@ -602,7 +605,7 @@ block: # bug #19857
doAssert v.kind == VFloat
case v.kind
of VFloat: result = v.fnum
else: discard
else: result = 0.0
proc foo() =
@@ -611,6 +614,7 @@ block: # bug #19857
# works:
#result = Value(kind: VFloat, fnum: fuck["field_that_does_not_exist"].float)
# broken:
result = Value()
discard "actuall runs!"
let t = fuck["field_that_does_not_exist"]
echo "never runs, but we crash after! ", t
@@ -638,7 +642,7 @@ method process*(self: App): Option[Event] {.base.} =
# bug #21617
type Test2 = ref object of RootObj
method bug(t: Test2): seq[float] {.base.} = discard
method bug(t: Test2): seq[float] {.base.} = result = @[]
block: # bug #22664
type
@@ -674,6 +678,7 @@ block: # bug #19250
Bar[T](err: err)
proc foo(): Foo[char] =
result = Foo[char]()
result.run = proc(): Bar[char] =
# works
# result = Bar[char](err: proc(): string = "x")
@@ -681,6 +686,7 @@ block: # bug #19250
result = bar[char](proc(): string = "x")
proc bug[T](fs: Foo[T]): Foo[T] =
result = Foo[T]()
result.run = proc(): Bar[T] =
let res = fs.run()
@@ -688,10 +694,11 @@ block: # bug #19250
# var errors = @[res.err]
# not work
var errors: seq[proc(): string]
var errors: seq[proc(): string] = @[]
errors.add res.err
return bar[T] do () -> string:
result = ""
for err in errors:
result.add res.err()

View File

@@ -166,7 +166,7 @@ type
x2: string
proc test_myobject =
var x: MyObject
var x: MyObject = MyObject()
x.x1 = "x1"
x.x2 = "x2"
x.y1 = "ljhkjhkjh"
@@ -213,6 +213,7 @@ type
error*: string
proc init(): RocksDBResult[string] =
result = default(RocksDBResult[string])
{.cast(uncheckedAssign).}:
result.ok = true
result.value = "ok"

View File

@@ -165,7 +165,7 @@ type
x2: string
proc test_myobject =
var x: MyObject
var x: MyObject = MyObject()
x.x1 = "x1"
x.x2 = "x2"
x.y1 = "ljhkjhkjh"
@@ -211,6 +211,7 @@ type
error*: string
proc init(): RocksDBResult[string] =
result = default(RocksDBResult[string])
{.cast(uncheckedAssign).}:
result.ok = true
result.value = "ok"

View File

@@ -33,7 +33,7 @@ proc addEdge(self: Graph; source, neighbor: Node) =
source.neighbors.add(Edge(neighbor: neighbor))
proc main =
var graph: Graph
var graph: Graph = Graph()
let nodeA = graph.addNode("a")
let nodeB = graph.addNode("b")
let nodeC = graph.addNode("c")

View File

@@ -38,12 +38,14 @@ proc add*(self: Config, param, value, section: string) {.nosinks.} =
# ----------------------------------------------------------------------------------------------------------------------
proc sections*(self: Config): seq[string] =
result = @[]
for i in self.table.keys:
let s = if i == defaultSection: "" else: i
result.add(s)
# ----------------------------------------------------------------------------------------------------------------------
proc params*(self: Config, section: string): seq[string] =
result = @[]
let s = if section == "": defaultSection else: section
if self.table.contains(s):

View File

@@ -125,9 +125,12 @@ template `[]=`*[T](x: myseq[T]; i: Natural; y: T) =
x.data[i] = y
proc createSeq*[T](elems: varargs[T]): myseq[T] =
result.cap = max(elems.len, 2)
result.len = elems.len
result = myseq[T](
cap: max(elems.len, 2),
len: elems.len)
result.data = cast[type(result.data)](alloc0(result.cap * sizeof(T)))
inc allocCount
when supportsCopyMem(T):
copyMem(result.data, addr(elems[0]), result.cap * sizeof(T))

View File

@@ -31,10 +31,10 @@ type
value: int
proc mainB =
var x: PBinaryTree
var x: PBinaryTree = nil
deepCopy(x, PBinaryTree(ri: PBinaryTree(le: PBinaryTree(value: 13))))
var y: string
var y: string = ""
deepCopy y, "abc"
echo x.ri.le.value, " ", y
@@ -55,7 +55,7 @@ proc `=deepCopy`[T](b: ref Bar[T]): ref Bar[T] =
echo "called deepCopy for something else"
proc main =
var dummy, c: ref Bar[int]
var dummy, c: ref Bar[int] = nil
new(dummy)
dummy.x = 44

View File

@@ -41,6 +41,7 @@ proc newFuture(s: string): Future =
var q: HeapQueue[tuple[finishAt: int64, fut: Future]]
proc sleep(f: int64): Future =
result = nil
q.push (finishAt: f, fut: newFuture("async-sleep"))
proc processTimers =

View File

@@ -35,6 +35,7 @@ type
id: ptr int
proc `=dup`(x: RefCustom): RefCustom =
result = RefCustom()
result.id = x.id
proc inc(x: sink Ref) =

View File

@@ -19,7 +19,7 @@ proc `=copy`(x: var FuncObj, y: FuncObj) {.error.}
# bug #18433
proc main =
var fs: seq[FuncObj]
var fs: seq[FuncObj] = @[]
proc wrap(p: proc()) =
proc closeOver() = p()

View File

@@ -140,7 +140,7 @@ proc main =
"Algorithmic error finding first 20 Hamming numbers!!!"
when not defined(trace20):
var lsth: TriVal
var lsth: TriVal = default(TriVal)
for h in hammings(200): lsth = h
doAssert $lsth.convertTriVal2BigInt == "16200",
"Algorithmic error finding 200th Hamming number!!!"

View File

@@ -102,25 +102,26 @@ for i in 0..1000:
proc lambdaTest2(a: MyAligned, z: ref MyAligned): auto =
var x1: MyAligned
var x1: MyAligned = default(MyAligned)
x1.a = a.a + z.a
var x2: MyAligned
var x2: MyAligned = default(MyAligned)
x2.a = a.a - z.a
let capturingLambda = proc(x: MyAligned): MyAligned =
var cc: MyAligned
var bb: MyAligned
result = default(MyAligned)
var cc: MyAligned = default(MyAligned)
var bb: MyAligned = default(MyAligned)
isAlignedCheck(x1.addr, MyAligned.alignOf)
isAlignedCheck(x2.addr, MyAligned.alignOf)
isAlignedCheck(cc.addr, MyAligned.alignOf)
isAlignedCheck(bb.addr, MyAligned.alignOf)
isAlignedCheck(z, MyAligned.alignOf)
cc.a = x1.a + x1.a + z.a
bb.a = x2.a - z.a
isAlignedCheck(result.addr, MyAligned.alignOf)
result.a = cc.a + bb.a + x2.a
return capturingLambda

View File

@@ -34,6 +34,7 @@ type
startNode: ref BasicBlock
proc newCfg(): Cfg =
result = Cfg()
result.basicBlockMap = initTable[int, ref BasicBlock]()
result.edgeList = newSeq[BasicBlockEdge]()
@@ -120,6 +121,7 @@ proc addLoop(self: var Lsg, l: ref SimpleLoop) =
self.loops.add l
proc newLsg(): Lsg =
result = Lsg()
result.loops = newSeq[ref SimpleLoop]()
result.root = result.createNewLoop()
result.root.setNestingLevel(0)
@@ -182,6 +184,7 @@ type
lsg: Lsg
proc newHavlakLoopFinder(cfg: sink Cfg, lsg: sink Lsg): HavlakLoopFinder =
result = HavlakLoopFinder()
result.cfg = cfg
result.lsg = lsg
@@ -366,6 +369,7 @@ type
lsg: Lsg
proc newLoopTesterApp(): LoopTesterApp =
result = LoopTesterApp()
result.cfg = newCfg()
result.lsg = newLsg()

View File

@@ -55,7 +55,7 @@ proc buildList(): PNode =
result.prev.prev = result.next
proc blockB =
var test3: TestObj
var test3: TestObj = TestObj()
test3.test = 42
test3.test2 = blah
testit(test3)

View File

@@ -10,6 +10,7 @@ discard """
import std / [os, strutils]
proc finOp2(path, name: string): (string, File) = # Find & open FIRST `name`
result = default((string, File))
var current = path
while true:
if current.isRootDir: break # <- current=="" => current.isRootDir

View File

@@ -786,6 +786,7 @@ main3()
# misc
proc smoltest(x: bool): bool =
result = false
while true:
if true: return x
@@ -832,6 +833,7 @@ proc convoluted =
let _ = (;
var val1: string;
if true: val1 = "22"
else: val1 = ""
true
)

View File

@@ -22,6 +22,7 @@ method `$`(token: Paragraph): string =
if token.children.head == nil:
result = ""
else:
result = ""
for c in token.children:
result.add $c
@@ -69,7 +70,7 @@ type holder = object
contents: outer
proc main() =
var t: holder
var t: holder = holder()
t.contents = newOuter()
main()

View File

@@ -40,6 +40,7 @@ var
lvalue
lnext
tmpTupleAsgn
result = default(Maybe)
lresult = @[123]
tmpTupleAsgn = (
let blitTmp = lresult
@@ -227,6 +228,7 @@ type
value: seq[int]
proc p1(): Maybe =
result = default(Maybe)
let lresult = @[123]
var lvalue: seq[int]
var lnext: string
@@ -248,7 +250,7 @@ proc tt(x: KeyValue) =
echo a
proc encodedQuery =
var query: seq[KeyValue]
var query: seq[KeyValue] = @[]
query.add (key: @[1], val: @[2])
for elem in query:

View File

@@ -64,7 +64,7 @@ proc f(): seq[int] =
@[1, 2, 3]
proc main(cond: bool) =
var a, b: seq[seq[int]]
var a, b: seq[seq[int]] = @[]
var x = f()
if cond:
a.add x
@@ -78,7 +78,7 @@ main(false)
proc tfor(cond: bool) =
var a, b: seq[seq[int]]
var a, b: seq[seq[int]] = @[]
var x = f()

View File

@@ -56,6 +56,7 @@ type
peers*: Table[PeerID, PubSubPeer]
proc getOrCreatePeer*(myParam: PubSub, peerId: PeerID, protos: seq[string]): PubSubPeer =
result = nil
myParam.peers.withValue(peerId, peer):
return peer[]

View File

@@ -31,7 +31,7 @@ proc myproc2(t: MyType) =
echo repr(x)
proc myproc3(t: MyType) =
var x: TableRef[string, t]
var x: TableRef[string, t] = nil
echo repr(x)

View File

@@ -72,7 +72,7 @@ proc newRStarTree*[M, D: Dim; RT, LT](minFill: range[30 .. 50] = 40): RStarTree[
result.root = newLeaf[M, D, RT, LT]()
proc center(r: Box): auto =#BoxCenter[r.len, typeof(r[0].a)] =
var res: BoxCenter[r.len, typeof(r[0].a)]
var res = default(BoxCenter[r.len, typeof(r[0].a)])
for i in 0 .. r.high:
when r[0].a is SomeInteger:
res[i] = (r[i].a + r[i].b) div 2
@@ -82,7 +82,7 @@ proc center(r: Box): auto =#BoxCenter[r.len, typeof(r[0].a)] =
return res
proc distance(c1, c2: BoxCenter): auto =
var res: typeof(c1[0])
var res: typeof(c1[0]) = default(typeof(c1[0]))
for i in 0 .. c1.high:
res += (c1[i] - c2[i]) * (c1[i] - c2[i])
return res
@@ -94,6 +94,7 @@ proc overlap(r1, r2: Box): auto =
if result <= 0: return 0
proc union(r1, r2: Box): Box =
result = default(Box)
for i in 0 .. r1.high:
result[i].a = min(r1[i].a, r2[i].a)
result[i].b = max(r1[i].b, r2[i].b)
@@ -178,7 +179,7 @@ proc chooseSubtree[M, D: Dim; RT, LT](t: RTree[M, D, RT, LT]; b: Box[D, RT]; lev
return it
proc pickSeeds[M, D: Dim; RT, LT](t: RTree[M, D, RT, LT]; n: Node[M, D, RT, LT] | Leaf[M, D, RT, LT]; bx: Box[D, RT]): (int, int) =
var i0, j0: int
var i0, j0: int = 0
var bi, bj: typeof(bx)
var largestWaste = typeof(bx[0].a).low
for i in -1 .. n.a.high:
@@ -198,6 +199,7 @@ proc pickSeeds[M, D: Dim; RT, LT](t: RTree[M, D, RT, LT]; n: Node[M, D, RT, LT]
return (i0, j0)
proc pickNext[M, D: Dim; RT, LT](t: RTree[M, D, RT, LT]; n0, n1, n2: Node[M, D, RT, LT] | Leaf[M, D, RT, LT]; b1, b2: Box[D, RT]): int =
result = 0
let a1 = area(b1)
let a2 = area(b2)
var d = typeof(a1).low
@@ -227,7 +229,7 @@ proc rstarSplit[M, D: Dim; RT, LT](t: RStarTree[M, D, RT, LT]; n: var Node[M, D,
var lx = lx
when n is Node[M, D, RT, LT]:
lx.n.parent = n
var lxbest: typeof(lx)
var lxbest: typeof(lx) = default(typeof(lx))
var m0 = lx.b[0].a.typeof.high
for d2 in 0 ..< 2 * D:
let d = d2 div 2
@@ -361,7 +363,7 @@ proc adjustTree[M, D: Dim; RT, LT](t: RTree[M, D, RT, LT]; l, ll: H[M, D, RT, LT
var i = 0
while p.a[i].n != n:
inc(i)
var b: typeof(p.a[0].b)
var b: typeof(p.a[0].b) = default(typeof(p.a[0].b))
if n of Leaf[M, D, RT, LT]:
when false:#if likely(nn.isNil): # no performance gain
b = union(p.a[i].b, Leaf[M, D, RT, LT](n).a[n.numEntries - 1].b)
@@ -429,7 +431,7 @@ proc rsinsert[M, D: Dim; RT, LT](t: RStarTree[M, D, RT, LT]; leaf: N[M, D, RT, L
proc reInsert[M, D: Dim; RT, LT](t: RStarTree[M, D, RT, LT]; n: var Node[M, D, RT, LT] | var Leaf[M, D, RT, LT]; lx: L[D, RT, LT] | N[M, D, RT, LT]) =
type NL = typeof(lx)
var lx = lx
var buf: typeof(n.a)
var buf: typeof(n.a) = default(typeof(n.a))
let p = Node[M, D, RT, LT](n.parent)
var i = 0
while p.a[i].n != n:
@@ -510,7 +512,7 @@ proc findLeaf[M, D: Dim; RT, LT](t: RTree[M, D, RT, LT]; leaf: L[D, RT, LT]): Le
proc condenseTree[M, D: Dim; RT, LT](t: RTree[M, D, RT, LT]; leaf: Leaf[M, D, RT, LT]) =
var n: H[M, D, RT, LT] = leaf
var q = newSeq[H[M, D, RT, LT]]()
var b: typeof(leaf.a[0].b)
var b: typeof(leaf.a[0].b) = default(typeof(leaf.a[0].b))
while n != t.root:
let p = Node[M, D, RT, LT](n.parent)
var i = 0
@@ -592,6 +594,7 @@ proc rseq_search(rs: RSeq; rse: RSE): seq[int] =
result.add(i.l)
proc rseq_delete(rs: var RSeq; rse: RSE): bool =
result = false
for i in 0 .. rs.high:
if rs[i] == rse:
#rs.delete(i)
@@ -602,7 +605,7 @@ proc rseq_delete(rs: var RSeq; rse: RSE): bool =
import random, algorithm
proc test(n: int) =
var b: Box[2, int]
var b: Box[2, int] = default(Box[2, int])
echo center(b)
var x1, x2, y1, y2: int
var t = newRStarTree[8, 2, int, int]()

View File

@@ -26,6 +26,7 @@ proc `=copy`*[T](dest: var SharedPtr[T], src: SharedPtr[T]) =
dest.val = src.val
proc newSharedPtr*[T](val: sink T): SharedPtr[T] {.nodestroy.} =
result = SharedPtr[T]()
result.val = cast[typeof(result.val)](allocShared(sizeof(result.val[])))
result.val.atomicCounter = 0
result.val.value = val

View File

@@ -118,7 +118,7 @@ when isMainModule:
# chan <- 53
# chan <- 64
Worker(Receiver):
var val: int
var val: int = 0
for j in 0 ..< 10:
args.chan[].recvLoop(val):
# Busy loop, in prod we might want to yield the core/thread timeslice
@@ -138,7 +138,7 @@ when isMainModule:
proc main() =
echo "Testing if 2 threads can send data"
echo "-----------------------------------"
var threads: array[2, Thread[ThreadArgs]]
var threads: array[2, Thread[ThreadArgs]] = default(array[2, Thread[ThreadArgs]])
var chan = cast[ptr ChannelSPSCSingle](allocShared(MemBlockSize))
chan[].initialize(itemSize = sizeof(int))

View File

@@ -115,7 +115,7 @@ when isMainModule:
# chan <- 53
# chan <- 64
Worker(Receiver):
var val: int
var val: int = 0
for j in 0 ..< 10:
args.chan[].recvLoop(val):
# Busy loop, in prod we might want to yield the core/thread timeslice
@@ -135,7 +135,7 @@ when isMainModule:
proc main() =
echo "Testing if 2 threads can send data"
echo "-----------------------------------"
var threads: array[2, Thread[ThreadArgs]]
var threads: array[2, Thread[ThreadArgs]] = default(array[2, Thread[ThreadArgs]])
var chan = cast[ptr ChannelSPSCSingle](allocShared(MemBlockSize))
chan[].initialize(itemSize = sizeof(int))