diff --git a/compiler/aliasanalysis.nim b/compiler/aliasanalysis.nim index f14b815243..e24c6d8e26 100644 --- a/compiler/aliasanalysis.nim +++ b/compiler/aliasanalysis.nim @@ -74,7 +74,7 @@ proc aliases*(obj, field: PNode): AliasKind = # x[i] -> x[i]: maybe; Further analysis could make this return true when i is a runtime-constant # x[i] -> x[j]: maybe; also returns maybe if only one of i or j is a compiletime-constant template collectImportantNodes(result, n) = - var result: seq[PNode] + var result: seq[PNode] = @[] var n = n while true: case n.kind diff --git a/compiler/aliases.nim b/compiler/aliases.nim index 4b50fdb282..fa9824c41e 100644 --- a/compiler/aliases.nim +++ b/compiler/aliases.nim @@ -114,6 +114,8 @@ proc isPartOf*(a, b: PNode): TAnalysisResult = # use expensive type check: if isPartOf(a.sym.typ, b.sym.typ) != arNo: result = arMaybe + else: + result = arNo of nkBracketExpr: result = isPartOf(a[0], b[0]) if a.len >= 2 and b.len >= 2: @@ -149,7 +151,7 @@ proc isPartOf*(a, b: PNode): TAnalysisResult = result = isPartOf(a[1], b[1]) of nkObjUpConv, nkObjDownConv, nkCheckedFieldExpr: result = isPartOf(a[0], b[0]) - else: discard + else: result = arNo # Calls return a new location, so a default of ``arNo`` is fine. else: # go down recursively; this is quite demanding: @@ -165,6 +167,7 @@ proc isPartOf*(a, b: PNode): TAnalysisResult = of DerefKinds: # a* !<| b[] iff + result = arNo if isPartOf(a.typ, b.typ) != arNo: result = isPartOf(a, b[0]) if result == arNo: result = arMaybe @@ -186,7 +189,9 @@ proc isPartOf*(a, b: PNode): TAnalysisResult = if isPartOf(a.typ, b.typ) != arNo: result = isPartOf(a[0], b) if result == arNo: result = arMaybe - else: discard + else: + result = arNo + else: result = arNo of nkObjConstr: result = arNo for i in 1.. 0: result = isPartOf(a, b[0]) - else: discard + else: + result = arNo + else: result = arNo diff --git a/compiler/ast.nim b/compiler/ast.nim index 539b6e9547..eccf5a9852 100644 --- a/compiler/ast.nim +++ b/compiler/ast.nim @@ -1036,6 +1036,8 @@ proc comment*(n: PNode): string = if nfHasComment in n.flags and not gconfig.useIc: # IC doesn't track comments, see `packed_ast`, so this could fail result = gconfig.comments[n.nodeId] + else: + result = "" proc `comment=`*(n: PNode, a: string) = let id = n.nodeId @@ -1222,6 +1224,7 @@ proc getDeclPragma*(n: PNode): PNode = case n.kind of routineDefs: if n[pragmasPos].kind != nkEmpty: result = n[pragmasPos] + else: result = nil of nkTypeDef: #[ type F3*{.deprecated: "x3".} = int @@ -1241,6 +1244,8 @@ proc getDeclPragma*(n: PNode): PNode = ]# if n[0].kind == nkPragmaExpr: result = n[0][1] + else: + result = nil else: # support as needed for `nkIdentDefs` etc. result = nil @@ -1256,6 +1261,12 @@ proc extractPragma*(s: PSym): PNode = if s.ast[0].kind == nkPragmaExpr and s.ast[0].len > 1: # s.ast = nkTypedef / nkPragmaExpr / [nkSym, nkPragma] result = s.ast[0][1] + else: + result = nil + else: + result = nil + else: + result = nil assert result == nil or result.kind == nkPragma proc skipPragmaExpr*(n: PNode): PNode = @@ -1602,6 +1613,7 @@ proc initStrTable*(x: var TStrTable) = newSeq(x.data, StartSize) proc newStrTable*: TStrTable = + result = default(TStrTable) initStrTable(result) proc initIdTable*(x: var TIdTable) = @@ -1609,6 +1621,7 @@ proc initIdTable*(x: var TIdTable) = newSeq(x.data, StartSize) proc newIdTable*: TIdTable = + result = default(TIdTable) initIdTable(result) proc resetIdTable*(x: var TIdTable) = @@ -1811,6 +1824,7 @@ proc hasNilSon*(n: PNode): bool = result = false proc containsNode*(n: PNode, kinds: TNodeKinds): bool = + result = false if n == nil: return case n.kind of nkEmpty..nkNilLit: result = n.kind in kinds @@ -2012,6 +2026,8 @@ proc isImportedException*(t: PType; conf: ConfigRef): bool = if base.sym != nil and {sfCompileToCpp, sfImportc} * base.sym.flags != {}: result = true + else: + result = false proc isInfixAs*(n: PNode): bool = return n.kind == nkInfix and n[0].kind == nkIdent and n[0].ident.s == "as" diff --git a/compiler/astalgo.nim b/compiler/astalgo.nim index 4e09fab02f..d0aec085f5 100644 --- a/compiler/astalgo.nim +++ b/compiler/astalgo.nim @@ -197,6 +197,7 @@ proc getSymFromList*(list: PNode, ident: PIdent, start: int = 0): PSym = result = nil proc sameIgnoreBacktickGensymInfo(a, b: string): bool = + result = false if a[0] != b[0]: return false var alen = a.len - 1 while alen > 0 and a[alen] != '`': dec(alen) @@ -230,6 +231,7 @@ proc getNamedParamFromList*(list: PNode, ident: PIdent): PSym = ## result.add newIdentNode(getIdent(c.ic, x.name.s & "\`gensym" & $x.id), ## if c.instLines: actual.info else: templ.info) ## ``` + result = nil for i in 1.. 0: result.add ", " diff --git a/compiler/bitsets.nim b/compiler/bitsets.nim index 67598f9cae..756d93217c 100644 --- a/compiler/bitsets.nim +++ b/compiler/bitsets.nim @@ -87,5 +87,6 @@ const populationCount: array[uint8, uint8] = block: arr proc bitSetCard*(x: TBitSet): BiggestInt = + result = 0 for it in x: result.inc int(populationCount[it]) diff --git a/compiler/btrees.nim b/compiler/btrees.nim index 92f07f6b09..3b737b1bc9 100644 --- a/compiler/btrees.nim +++ b/compiler/btrees.nim @@ -38,6 +38,7 @@ template less(a, b): bool = cmp(a, b) < 0 template eq(a, b): bool = cmp(a, b) == 0 proc getOrDefault*[Key, Val](b: BTree[Key, Val], key: Key): Val = + result = default(Val) var x = b.root while x.isInternal: for j in 0.. # seq = (typeof seq) incrSeq(&seq->Sup, sizeof(x)); # seq->data[seq->len-1] = x; - var a, b, dest, tmpL, call: TLoc + var a, b, dest, tmpL, call: TLoc = default(TLoc) initLocExpr(p, e[1], a) initLocExpr(p, e[2], b) let seqType = skipTypes(e[1].typ, {tyVar}) @@ -1369,7 +1377,7 @@ proc genSeqElemAppend(p: BProc, e: PNode, d: var TLoc) = gcUsage(p.config, e) proc genReset(p: BProc, n: PNode) = - var a: TLoc + var a: TLoc = default(TLoc) initLocExpr(p, n[1], a) specializeReset(p, a) when false: @@ -1384,7 +1392,7 @@ proc genDefault(p: BProc; n: PNode; d: var TLoc) = proc rawGenNew(p: BProc, a: var TLoc, sizeExpr: Rope; needsInit: bool) = var sizeExpr = sizeExpr let typ = a.t - var b: TLoc + var b: TLoc = default(TLoc) initLoc(b, locExpr, a.lode, OnHeap) let refType = typ.skipTypes(abstractInstOwned) assert refType.kind == tyRef @@ -1411,7 +1419,7 @@ proc rawGenNew(p: BProc, a: var TLoc, sizeExpr: Rope; needsInit: bool) = localError(p.module.config, a.lode.info, "the destructor that is turned into a finalizer needs " & "to have the 'nimcall' calling convention") - var f: TLoc + var f: TLoc = default(TLoc) initLocExpr(p, newSymNode(op), f) p.module.s[cfsTypeInit3].addf("$1->finalizer = (void*)$2;$n", [ti, rdLoc(f)]) @@ -1437,11 +1445,11 @@ proc rawGenNew(p: BProc, a: var TLoc, sizeExpr: Rope; needsInit: bool) = genObjectInit(p, cpsStmts, bt, a, constructRefObj) proc genNew(p: BProc, e: PNode) = - var a: TLoc + var a: TLoc = default(TLoc) initLocExpr(p, e[1], a) # 'genNew' also handles 'unsafeNew': if e.len == 3: - var se: TLoc + var se: TLoc = default(TLoc) initLocExpr(p, e[2], se) rawGenNew(p, a, se.rdLoc, needsInit = true) else: @@ -1450,7 +1458,7 @@ proc genNew(p: BProc, e: PNode) = proc genNewSeqAux(p: BProc, dest: TLoc, length: Rope; lenIsZero: bool) = let seqtype = skipTypes(dest.t, abstractVarRange) - var call: TLoc + var call: TLoc = default(TLoc) initLoc(call, locExpr, dest.lode, OnHeap) if dest.storage == OnHeap and usesWriteBarrier(p.config): if canFormAcycle(p.module.g.graph, dest.t): @@ -1476,7 +1484,7 @@ proc genNewSeqAux(p: BProc, dest: TLoc, length: Rope; lenIsZero: bool) = genAssignment(p, dest, call, {}) proc genNewSeq(p: BProc, e: PNode) = - var a, b: TLoc + var a, b: TLoc = default(TLoc) initLocExpr(p, e[1], a) initLocExpr(p, e[2], b) if optSeqDestructors in p.config.globalOptions: @@ -1492,7 +1500,7 @@ proc genNewSeq(p: BProc, e: PNode) = proc genNewSeqOfCap(p: BProc; e: PNode; d: var TLoc) = let seqtype = skipTypes(e.typ, abstractVarRange) - var a: TLoc + var a: TLoc = default(TLoc) initLocExpr(p, e[1], a) if optSeqDestructors in p.config.globalOptions: if d.k == locNone: getTemp(p, e.typ, d, needsInit=false) @@ -1548,7 +1556,7 @@ proc genObjConstr(p: BProc, e: PNode, d: var TLoc) = (d.k notin {locTemp,locLocalVar,locGlobalVar,locParam,locField}) or (isPartOf(d.lode, e) != arNo) - var tmp: TLoc + var tmp: TLoc = default(TLoc) var r: Rope if useTemp: getTemp(p, t, tmp) @@ -1567,7 +1575,7 @@ proc genObjConstr(p: BProc, e: PNode, d: var TLoc) = let ty = getUniqueType(t) for i in 1..>3] &(1U<<((NU)($2)&7U)))!=0)") template binaryStmtInExcl(p: BProc, e: PNode, d: var TLoc, frmt: string) = - var a, b: TLoc + var a, b: TLoc = default(TLoc) assert(d.k == locNone) initLocExpr(p, e[1], a) initLocExpr(p, e[2], b) @@ -2031,7 +2040,7 @@ template binaryStmtInExcl(p: BProc, e: PNode, d: var TLoc, frmt: string) = lineF(p, cpsStmts, frmt, [rdLoc(a), elem]) proc genInOp(p: BProc, e: PNode, d: var TLoc) = - var a, b, x, y: TLoc + var a, b, x, y: TLoc = default(TLoc) if (e[1].kind == nkCurly) and fewCmps(p.config, e[1]): # a set constructor but not a constant set: # do not emit the set, but generate a bunch of comparisons; and if we do @@ -2081,7 +2090,7 @@ proc genSetOp(p: BProc, e: PNode, d: var TLoc, op: TMagic) = "&", "|", "& ~"] - var a, b, i: TLoc + var a, b, i: TLoc = default(TLoc) var setType = skipTypes(e[1].typ, abstractVar) var size = int(getSize(p.config, setType)) case size @@ -2118,7 +2127,7 @@ proc genSetOp(p: BProc, e: PNode, d: var TLoc, op: TMagic) = of mIncl: binaryStmtInExcl(p, e, d, "$1[(NU)($2)>>3] |=(1U<<($2&7U));$n") of mExcl: binaryStmtInExcl(p, e, d, "$1[(NU)($2)>>3] &= ~(1U<<($2&7U));$n") of mCard: - var a: TLoc + var a: TLoc = default(TLoc) initLocExpr(p, e[1], a) putIntoDest(p, d, e, ropecg(p.module, "#cardSet($1, $2)", [addrLoc(p.config, a), size])) of mLtSet, mLeSet: @@ -2133,7 +2142,7 @@ proc genSetOp(p: BProc, e: PNode, d: var TLoc, op: TMagic) = linefmt(p, cpsStmts, lookupOpr[mLeSet], [rdLoc(i), size, rdLoc(d), rdLoc(a), rdLoc(b)]) of mEqSet: - var a, b: TLoc + var a, b: TLoc = default(TLoc) assert(e[1].typ != nil) assert(e[2].typ != nil) initLocExpr(p, e[1], a) @@ -2161,7 +2170,7 @@ proc genSomeCast(p: BProc, e: PNode, d: var TLoc) = ValueTypes = {tyTuple, tyObject, tyArray, tyOpenArray, tyVarargs, tyUncheckedArray} # we use whatever C gives us. Except if we have a value-type, we need to go # through its address: - var a: TLoc + var a: TLoc = default(TLoc) initLocExpr(p, e[1], a) let etyp = skipTypes(e.typ, abstractRange+{tyOwned}) let srcTyp = skipTypes(e[1].typ, abstractRange) @@ -2199,7 +2208,7 @@ proc genCast(p: BProc, e: PNode, d: var TLoc) = # 'cast' and some float type involved? --> use a union. inc(p.labels) var lbl = p.labels.rope - var tmp: TLoc + var tmp: TLoc = default(TLoc) tmp.r = "LOC$1.source" % [lbl] let destsize = getSize(p.config, destt) let srcsize = getSize(p.config, srct) @@ -2222,7 +2231,7 @@ proc genCast(p: BProc, e: PNode, d: var TLoc) = genSomeCast(p, e, d) proc genRangeChck(p: BProc, n: PNode, d: var TLoc) = - var a: TLoc + var a: TLoc = default(TLoc) var dest = skipTypes(n.typ, abstractVar) initLocExpr(p, n[0], a) if optRangeCheck notin p.options or (dest.kind in {tyUInt..tyUInt64} and @@ -2277,7 +2286,7 @@ proc genConv(p: BProc, e: PNode, d: var TLoc) = genSomeCast(p, e, d) proc convStrToCStr(p: BProc, n: PNode, d: var TLoc) = - var a: TLoc + var a: TLoc = default(TLoc) initLocExpr(p, n[0], a) putIntoDest(p, d, n, ropecg(p.module, "#nimToCStringConv($1)", [rdLoc(a)]), @@ -2285,7 +2294,7 @@ proc convStrToCStr(p: BProc, n: PNode, d: var TLoc) = a.storage) proc convCStrToStr(p: BProc, n: PNode, d: var TLoc) = - var a: TLoc + var a: TLoc = default(TLoc) initLocExpr(p, n[0], a) putIntoDest(p, d, n, ropecg(p.module, "#cstrToNimstr($1)", [rdLoc(a)]), @@ -2293,7 +2302,7 @@ proc convCStrToStr(p: BProc, n: PNode, d: var TLoc) = gcUsage(p.config, n) proc genStrEquals(p: BProc, e: PNode, d: var TLoc) = - var x: TLoc + var x: TLoc = default(TLoc) var a = e[1] var b = e[2] if a.kind in {nkStrLit..nkTripleStrLit} and a.strVal == "": @@ -2310,7 +2319,7 @@ proc genStrEquals(p: BProc, e: PNode, d: var TLoc) = proc binaryFloatArith(p: BProc, e: PNode, d: var TLoc, m: TMagic) = if {optNaNCheck, optInfCheck} * p.options != {}: const opr: array[mAddF64..mDivF64, string] = ["+", "-", "*", "/"] - var a, b: TLoc + var a, b: TLoc = default(TLoc) assert(e[1].typ != nil) assert(e[2].typ != nil) initLocExpr(p, e[1], a) @@ -2335,7 +2344,7 @@ proc skipAddr(n: PNode): PNode = result = if n.kind in {nkAddr, nkHiddenAddr}: n[0] else: n proc genWasMoved(p: BProc; n: PNode) = - var a: TLoc + var a: TLoc = default(TLoc) let n1 = n[1].skipAddr if p.withinBlockLeaveActions > 0 and notYetAlive(n1): discard @@ -2346,11 +2355,11 @@ proc genWasMoved(p: BProc; n: PNode) = # [addrLoc(p.config, a), getTypeDesc(p.module, a.t)]) proc genMove(p: BProc; n: PNode; d: var TLoc) = - var a: TLoc + var a: TLoc = default(TLoc) initLocExpr(p, n[1].skipAddr, a) if n.len == 4: # generated by liftdestructors: - var src: TLoc + var src: TLoc = default(TLoc) initLocExpr(p, n[2], src) linefmt(p, cpsStmts, "if ($1.p != $2.p) {", [rdLoc(a), rdLoc(src)]) genStmts(p, n[3]) @@ -2377,7 +2386,7 @@ proc genDestroy(p: BProc; n: PNode) = let t = arg.typ.skipTypes(abstractInst) case t.kind of tyString: - var a: TLoc + var a: TLoc = default(TLoc) initLocExpr(p, arg, a) if optThreads in p.config.globalOptions: linefmt(p, cpsStmts, "if ($1.p && !($1.p->cap & NIM_STRLIT_FLAG)) {$n" & @@ -2388,7 +2397,7 @@ proc genDestroy(p: BProc; n: PNode) = " #dealloc($1.p);$n" & "}$n", [rdLoc(a)]) of tySequence: - var a: TLoc + var a: TLoc = default(TLoc) initLocExpr(p, arg, a) linefmt(p, cpsStmts, "if ($1.p && !($1.p->cap & NIM_STRLIT_FLAG)) {$n" & " #alignedDealloc($1.p, NIM_ALIGNOF($2));$n" & @@ -2406,7 +2415,7 @@ proc genDispose(p: BProc; n: PNode) = when false: let elemType = n[1].typ.skipTypes(abstractVar).lastSon - var a: TLoc + var a: TLoc = default(TLoc) initLocExpr(p, n[1].skipAddr, a) if isFinal(elemType): @@ -2459,7 +2468,7 @@ proc genMagicExpr(p: BProc, e: PNode, d: var TLoc, op: TMagic) = if optOverflowCheck notin p.options or underlying.kind in {tyUInt..tyUInt64}: binaryStmt(p, e, d, opr[op]) else: - var a, b: TLoc + var a, b: TLoc = default(TLoc) assert(e[1].typ != nil) assert(e[2].typ != nil) initLocExpr(p, e[1], a) @@ -2477,7 +2486,7 @@ proc genMagicExpr(p: BProc, e: PNode, d: var TLoc, op: TMagic) = if optSeqDestructors in p.config.globalOptions: binaryStmtAddr(p, e, d, "nimAddCharV1") else: - var dest, b, call: TLoc + var dest, b, call: TLoc = default(TLoc) initLoc(call, locCall, e, OnHeap) initLocExpr(p, e[1], dest) initLocExpr(p, e[2], b) @@ -2515,7 +2524,7 @@ proc genMagicExpr(p: BProc, e: PNode, d: var TLoc, op: TMagic) = of mNew: genNew(p, e) of mNewFinalize: if optTinyRtti in p.config.globalOptions: - var a: TLoc + var a: TLoc = default(TLoc) initLocExpr(p, e[1], a) rawGenNew(p, a, "", needsInit = true) gcUsage(p.config, e) @@ -2541,6 +2550,7 @@ proc genMagicExpr(p: BProc, e: PNode, d: var TLoc, op: TMagic) = elif e[1].kind == nkCheckedFieldExpr: dotExpr = e[1][0] else: + dotExpr = nil internalError(p.config, e.info, "unknown ast") let t = dotExpr[0].typ.skipTypes({tyTypeDesc}) let tname = getTypeDesc(p.module, t, dkVar) @@ -2609,7 +2619,7 @@ proc genMagicExpr(p: BProc, e: PNode, d: var TLoc, op: TMagic) = localError(p.config, e.info, "for --gc:arc|orc 'deepcopy' support has to be enabled with --deepcopy:on") - var a, b: TLoc + var a, b: TLoc = default(TLoc) let x = if e[1].kind in {nkAddr, nkHiddenAddr}: e[1][0] else: e[1] initLocExpr(p, x, a) initLocExpr(p, e[2], b) @@ -2635,7 +2645,7 @@ proc genSetConstr(p: BProc, e: PNode, d: var TLoc) = # nimZeroMem(tmp, sizeof(tmp)); inclRange(tmp, a, b); incl(tmp, c); # incl(tmp, d); incl(tmp, e); inclRange(tmp, f, g); var - a, b, idx: TLoc + a, b, idx: TLoc = default(TLoc) if nfAllConst in e.flags: var elem = newRopeAppender() genSetNode(p, e, elem) @@ -2690,12 +2700,12 @@ proc genSetConstr(p: BProc, e: PNode, d: var TLoc) = [rdLoc(d), aa, rope(ts)]) proc genTupleConstr(p: BProc, n: PNode, d: var TLoc) = - var rec: TLoc + var rec: TLoc = default(TLoc) if not handleConstExpr(p, n, d): let t = n.typ discard getTypeDesc(p.module, t) # so that any fields are initialized - var tmp: TLoc + var tmp: TLoc = default(TLoc) # bug #16331 let doesAlias = lhsDoesAlias(d.lode, n) let dest = if doesAlias: addr(tmp) else: addr(d) @@ -2734,7 +2744,7 @@ proc genClosure(p: BProc, n: PNode, d: var TLoc) = p.module.s[cfsData].add data putIntoDest(p, d, n, tmp, OnStatic) else: - var tmp, a, b: TLoc + var tmp, a, b: TLoc = default(TLoc) initLocExpr(p, n[0], a) initLocExpr(p, n[1], b) if n[0].skipConv.kind == nkClosure: @@ -2751,7 +2761,7 @@ proc genClosure(p: BProc, n: PNode, d: var TLoc) = putLocIntoDest(p, d, tmp) proc genArrayConstr(p: BProc, n: PNode, d: var TLoc) = - var arr: TLoc + var arr: TLoc = default(TLoc) if not handleConstExpr(p, n, d): if d.k == locNone: getTemp(p, n.typ, d) for i in 0..Sup" else: ".Sup") for i in 2..abs(inheritanceDiff(dest, src)): r.add(".Sup") @@ -3049,7 +3059,7 @@ proc expr(p: BProc, n: PNode, d: var TLoc) = let op = n[0] if n.typ.isNil: # discard the value: - var a: TLoc + var a: TLoc = default(TLoc) if op.kind == nkSym and op.sym.magic != mNone: genMagicExpr(p, n, a, op.sym.magic) else: @@ -3143,7 +3153,7 @@ proc expr(p: BProc, n: PNode, d: var TLoc) = let ex = n[0] if ex.kind != nkEmpty: genLineDir(p, n) - var a: TLoc + var a: TLoc = default(TLoc) initLocExprSingleUse(p, ex, a) line(p, cpsStmts, "(void)(" & a.r & ");\L") of nkAsmStmt: genAsmStmt(p, n) @@ -3254,6 +3264,7 @@ proc getDefaultValue(p: BProc; typ: PType; info: TLineInfo; result: var Rope) = globalError(p.config, info, "cannot create null element for: " & $t.kind) proc caseObjDefaultBranch(obj: PNode; branch: Int128): int = + result = 0 for i in 1 ..< obj.len: for j in 0 .. obj[i].len - 2: if obj[i][j].kind == nkRange: @@ -3464,11 +3475,11 @@ proc genBracedInit(p: BProc, n: PNode; isConst: bool; optionalType: PType; resul if n[0].kind == nkNilLit: result.add "{NIM_NIL,NIM_NIL}" else: - var d: TLoc + var d: TLoc = default(TLoc) initLocExpr(p, n[0], d) result.add "{(($1) $2),NIM_NIL}" % [getClosureType(p.module, typ, clHalfWithEnv), rdLoc(d)] else: - var d: TLoc + var d: TLoc = default(TLoc) initLocExpr(p, n, d) result.add rdLoc(d) of tyArray, tyVarargs: @@ -3497,10 +3508,10 @@ proc genBracedInit(p: BProc, n: PNode; isConst: bool; optionalType: PType; resul if optSeqDestructors in p.config.globalOptions and n.kind != nkNilLit and ty == tyString: genStringLiteralV2Const(p.module, n, isConst, result) else: - var d: TLoc + var d: TLoc = default(TLoc) initLocExpr(p, n, d) result.add rdLoc(d) else: - var d: TLoc + var d: TLoc = default(TLoc) initLocExpr(p, n, d) result.add rdLoc(d) diff --git a/compiler/ccgreset.nim b/compiler/ccgreset.nim index 5e6456704d..f486f71fb7 100644 --- a/compiler/ccgreset.nim +++ b/compiler/ccgreset.nim @@ -57,7 +57,7 @@ proc specializeResetT(p: BProc, accessor: Rope, typ: PType) = specializeResetT(p, accessor, lastSon(typ)) of tyArray: let arraySize = lengthOrd(p.config, typ[0]) - var i: TLoc + var i: TLoc = default(TLoc) getTemp(p, getSysType(p.module.g.graph, unknownLineInfo, tyInt), i) linefmt(p, cpsStmts, "for ($1 = 0; $1 < $2; $1++) {$n", [i.r, arraySize]) diff --git a/compiler/ccgstmts.nim b/compiler/ccgstmts.nim index 3197389814..45104399a1 100644 --- a/compiler/ccgstmts.nim +++ b/compiler/ccgstmts.nim @@ -50,6 +50,7 @@ proc isAssignedImmediately(conf: ConfigRef; n: PNode): bool {.inline.} = result = true proc inExceptBlockLen(p: BProc): int = + result = 0 for x in p.nestedTryStmts: if x.inExcept: result.inc @@ -71,7 +72,7 @@ template startBlock(p: BProc, start: FormatStr = "{$n", proc endBlock(p: BProc) proc genVarTuple(p: BProc, n: PNode) = - var tup, field: TLoc + var tup, field: TLoc = default(TLoc) if n.kind != nkVarTuple: internalError(p.config, n.info, "genVarTuple") # if we have a something that's been captured, use the lowering instead: @@ -83,7 +84,7 @@ proc genVarTuple(p: BProc, n: PNode) = # check only the first son var forHcr = treatGlobalDifferentlyForHCR(p.module, n[0].sym) let hcrCond = if forHcr: getTempName(p.module) else: "" - var hcrGlobals: seq[tuple[loc: TLoc, tp: Rope]] + var hcrGlobals: seq[tuple[loc: TLoc, tp: Rope]] = @[] # determine if the tuple is constructed at top-level scope or inside of a block (if/while/block) let isGlobalInBlock = forHcr and p.blocks.len > 2 # do not close and reopen blocks if this is a 'global' but inside of a block (if/while/block) @@ -169,7 +170,7 @@ proc endBlock(p: BProc, blockEnd: Rope) = proc endBlock(p: BProc) = let topBlock = p.blocks.len - 1 let frameLen = p.blocks[topBlock].frameLen - var blockEnd: Rope + var blockEnd: Rope = "" if frameLen > 0: blockEnd.addf("FR_.len-=$1;$n", [frameLen.rope]) if p.blocks[topBlock].label.len != 0: @@ -244,7 +245,7 @@ proc genGotoState(p: BProc, n: PNode) = # switch (x.state) { # case 0: goto STATE0; # ... - var a: TLoc + var a: TLoc = default(TLoc) initLocExpr(p, n[0], a) lineF(p, cpsStmts, "switch ($1) {$n", [rdLoc(a)]) p.flags.incl beforeRetNeeded @@ -263,7 +264,7 @@ proc genGotoState(p: BProc, n: PNode) = lineF(p, cpsStmts, "}$n", []) proc genBreakState(p: BProc, n: PNode, d: var TLoc) = - var a: TLoc + var a: TLoc = default(TLoc) initLoc(d, locExpr, n, OnUnknown) if n[0].kind == nkClosure: @@ -357,7 +358,7 @@ proc genSingleVar(p: BProc, v: PSym; vn, value: PNode) = # generate better code here: 'Foo f = x;' genLineDir(p, vn) var decl = localVarDecl(p, vn) - var tmp: TLoc + var tmp: TLoc = default(TLoc) if isCppCtorCall: genCppVarForCtor(p, v, vn, value, decl) line(p, cpsStmts, decl) @@ -441,7 +442,7 @@ proc genIf(p: BProc, n: PNode, d: var TLoc) = # { elsePart } # Lend: var - a: TLoc + a: TLoc = default(TLoc) lelse: TLabel if not isEmptyType(n.typ) and d.k == locNone: getTemp(p, n.typ, d) @@ -520,7 +521,7 @@ proc genComputedGoto(p: BProc; n: PNode) = # wrapped inside stmt lists by inject destructors won't be recognised let n = n.flattenStmts() var casePos = -1 - var arraySize: int + var arraySize: int = 0 for i in 0.. 0: genIfForCaseUntil(p, n, d, rangeFormat = "if ($1 >= $2 && $1 <= $3) goto $4;$n", @@ -1389,7 +1392,7 @@ proc genTrySetjmp(p: BProc, t: PNode, d: var TLoc) = p.flags.incl noSafePoints genLineDir(p, t) cgsym(p.module, "Exception") - var safePoint: Rope + var safePoint: Rope = "" if not quirkyExceptions: safePoint = getTempName(p.module) linefmt(p, cpsLocals, "#TSafePoint $1;$n", [safePoint]) @@ -1492,7 +1495,7 @@ proc genAsmOrEmitStmt(p: BProc, t: PNode, isAsmStmt=false; result: var Rope) = of nkSym: var sym = it.sym if sym.kind in {skProc, skFunc, skIterator, skMethod}: - var a: TLoc + var a: TLoc = default(TLoc) initLocExpr(p, it, a) res.add($rdLoc(a)) elif sym.kind == skType: @@ -1505,7 +1508,7 @@ proc genAsmOrEmitStmt(p: BProc, t: PNode, isAsmStmt=false; result: var Rope) = res.add($getTypeDesc(p.module, it.typ)) else: discard getTypeDesc(p.module, skipTypes(it.typ, abstractPtrs)) - var a: TLoc + var a: TLoc = default(TLoc) initLocExpr(p, it, a) res.add($a.rdLoc) @@ -1608,7 +1611,7 @@ when false: expr(p, call, d) proc asgnFieldDiscriminant(p: BProc, e: PNode) = - var a, tmp: TLoc + var a, tmp: TLoc = default(TLoc) var dotExpr = e[0] if dotExpr.kind == nkCheckedFieldExpr: dotExpr = dotExpr[0] initLocExpr(p, e[0], a) @@ -1630,7 +1633,7 @@ proc genAsgn(p: BProc, e: PNode, fastAsgn: bool) = else: let le = e[0] let ri = e[1] - var a: TLoc + var a: TLoc = default(TLoc) discard getTypeDesc(p.module, le.typ.skipTypes(skipPtrs), dkVar) initLoc(a, locNone, le, OnUnknown) a.flags.incl(lfEnforceDeref) @@ -1644,7 +1647,7 @@ proc genAsgn(p: BProc, e: PNode, fastAsgn: bool) = loadInto(p, le, ri, a) proc genStmts(p: BProc, t: PNode) = - var a: TLoc + var a: TLoc = default(TLoc) let isPush = p.config.hasHint(hintExtendedContext) if isPush: pushInfoContext(p.config, t.info) diff --git a/compiler/ccgtrav.nim b/compiler/ccgtrav.nim index 96f5869b00..e4008bfc1e 100644 --- a/compiler/ccgtrav.nim +++ b/compiler/ccgtrav.nim @@ -74,7 +74,7 @@ proc genTraverseProc(c: TTraversalClosure, accessor: Rope, typ: PType) = genTraverseProc(c, accessor, lastSon(typ)) of tyArray: let arraySize = lengthOrd(c.p.config, typ[0]) - var i: TLoc + var i: TLoc = default(TLoc) getTemp(p, getSysType(c.p.module.g.graph, unknownLineInfo, tyInt), i) var oldCode = p.s(cpsStmts) freeze oldCode @@ -119,11 +119,11 @@ proc genTraverseProc(c: TTraversalClosure, accessor: Rope, typ: PType) = proc genTraverseProcSeq(c: TTraversalClosure, accessor: Rope, typ: PType) = var p = c.p assert typ.kind == tySequence - var i: TLoc + var i: TLoc = default(TLoc) getTemp(p, getSysType(c.p.module.g.graph, unknownLineInfo, tyInt), i) var oldCode = p.s(cpsStmts) freeze oldCode - var a: TLoc + var a: TLoc = default(TLoc) a.r = accessor lineF(p, cpsStmts, "for ($1 = 0; $1 < $2; $1++) {$n", diff --git a/compiler/ccgtypes.nim b/compiler/ccgtypes.nim index 2aa92c130e..205031a918 100644 --- a/compiler/ccgtypes.nim +++ b/compiler/ccgtypes.nim @@ -206,8 +206,12 @@ proc mapType(conf: ConfigRef; typ: PType; isParam: bool): TCTypeKind = result = TCTypeKind(ord(typ.kind) - ord(tyInt) + ord(ctInt)) of tyStatic: if typ.n != nil: result = mapType(conf, lastSon typ, isParam) - else: doAssert(false, "mapType: " & $typ.kind) - else: doAssert(false, "mapType: " & $typ.kind) + else: + result = ctVoid + doAssert(false, "mapType: " & $typ.kind) + else: + result = ctVoid + doAssert(false, "mapType: " & $typ.kind) proc mapReturnType(conf: ConfigRef; typ: PType): TCTypeKind = @@ -322,7 +326,9 @@ proc getSimpleTypeDesc(m: BModule; typ: PType): Rope = of tyDistinct, tyRange, tyOrdinal: result = getSimpleTypeDesc(m, typ[0]) of tyStatic: if typ.n != nil: result = getSimpleTypeDesc(m, lastSon typ) - else: internalError(m.config, "tyStatic for getSimpleTypeDesc") + else: + result = "" + internalError(m.config, "tyStatic for getSimpleTypeDesc") of tyGenericInst, tyAlias, tySink, tyOwned: result = getSimpleTypeDesc(m, lastSon typ) else: result = "" @@ -501,8 +507,8 @@ proc genMemberProcParams(m: BModule; prc: PSym, superCall, rettype, params: var rettype = getTypeDescAux(m, t[0], check, dkResult) else: rettype = runtimeFormat(rettype.replace("'0", "$1"), [getTypeDescAux(m, t[0], check, dkResult)]) - var types, names, args: seq[string] - if not isCtor: + var types, names, args: seq[string] = @[] + if not isCtor: var this = t.n[1].sym fillParamName(m, this) fillLoc(this.loc, locParam, t.n[1], @@ -719,9 +725,9 @@ proc getRecordFields(m: BModule; typ: PType, check: var IntSet): Rope = genRecordFieldsAux(m, typ.n, typ, check, result) if typ.itemId in m.g.graph.memberProcsPerType: let procs = m.g.graph.memberProcsPerType[typ.itemId] - var isDefaultCtorGen, isCtorGen: bool + var isDefaultCtorGen, isCtorGen: bool = false for prc in procs: - var header: Rope + var header: Rope = "" if sfConstructor in prc.flags: isCtorGen = true if prc.typ.n.len == 1: @@ -741,7 +747,8 @@ proc fillObjectFields*(m: BModule; typ: PType) = proc mangleDynLibProc(sym: PSym): Rope proc getRecordDescAux(m: BModule; typ: PType, name, baseType: Rope, - check: var IntSet, hasField:var bool): Rope = + check: var IntSet, hasField:var bool): Rope = + result = "" if typ.kind == tyObject: if typ[0] == nil: if lacksMTypeField(typ): @@ -782,7 +789,7 @@ proc getRecordDesc(m: BModule; typ: PType, name: Rope, structOrUnion = "#pragma pack(push, 1)\L" & structOrUnion(typ) else: structOrUnion = structOrUnion(typ) - var baseType: string + var baseType: string = "" if typ[0] != nil: baseType = getTypeDescAux(m, typ[0].skipTypes(skipPtrs), check, dkField) if typ.sym == nil or sfCodegenDecl notin typ.sym.flags: @@ -873,6 +880,7 @@ proc getTypeDescAux(m: BModule; origTyp: PType, check: var IntSet; kind: TypeDes if t != origTyp and origTyp.sym != nil: useHeader(m, origTyp.sym) let sig = hashType(origTyp, m.config) + result = "" # todo move `result = getTypePre(m, t, sig)` here ? defer: # defer is the simplest in this case if isImportedType(t) and not m.typeABICache.containsOrIncl(sig): addAbiCheck(m, t, result) @@ -953,7 +961,7 @@ proc getTypeDescAux(m: BModule; origTyp: PType, check: var IntSet; kind: TypeDes of tyProc: result = getTypeName(m, origTyp, sig) m.typeCache[sig] = result - var rettype, desc: Rope + var rettype, desc: Rope = "" genProcParams(m, t, rettype, desc, check, true, true) if not isImportedType(t): if t.callConv != ccClosure: # procedure vars may need a closure! @@ -1030,7 +1038,7 @@ proc getTypeDescAux(m: BModule; origTyp: PType, check: var IntSet; kind: TypeDes while i < cppName.len: if cppName[i] == '\'': var chunkEnd = i-1 - var idx, stars: int + var idx, stars: int = 0 if scanCppGenericSlot(cppName, i, idx, stars): result.add cppName.substr(chunkStart, chunkEnd) chunkStart = i @@ -1110,7 +1118,7 @@ proc getClosureType(m: BModule; t: PType, kind: TClosureTypeKind): Rope = assert t.kind == tyProc var check = initIntSet() result = getTempName(m) - var rettype, desc: Rope + var rettype, desc: Rope = "" genProcParams(m, t, rettype, desc, check, declareEnvironment=kind != clHalf) if not isImportedType(t): if t.callConv != ccClosure or kind != clFull: @@ -1141,7 +1149,7 @@ proc isNonReloadable(m: BModule; prc: PSym): bool = return m.hcrOn and sfNonReloadable in prc.flags proc parseVFunctionDecl(val: string; name, params, retType, superCall: var string; isFnConst, isOverride: var bool; isCtor: bool) = - var afterParams: string + var afterParams: string = "" if scanf(val, "$*($*)$s$*", name, params, afterParams): isFnConst = afterParams.find("const") > -1 isOverride = afterParams.find("override") > -1 @@ -1170,11 +1178,11 @@ proc genMemberProcHeader(m: BModule; prc: PSym; result: var Rope; asPtr: bool = memberOp = "#->" var typDesc = getTypeDescWeak(m, typ, check, dkParam) let asPtrStr = rope(if asPtr: "_PTR" else: "") - var name, params, rettype, superCall: string - var isFnConst, isOverride: bool + var name, params, rettype, superCall: string = "" + var isFnConst, isOverride: bool = false parseVFunctionDecl(prc.constraint.strVal, name, params, rettype, superCall, isFnConst, isOverride, isCtor) genMemberProcParams(m, prc, superCall, rettype, params, check, true, false) - var fnConst, override: string + var fnConst, override: string = "" if isCtor: name = typDesc if isFnConst: @@ -1203,7 +1211,7 @@ proc genProcHeader(m: BModule; prc: PSym; result: var Rope; asPtr: bool = false) var check = initIntSet() fillBackendName(m, prc) fillLoc(prc.loc, locProc, prc.ast[namePos], OnUnknown) - var rettype, params: Rope + var rettype, params: Rope = "" genProcParams(m, prc.typ, rettype, params, check, true, false) # handle the 2 options for hotcodereloading codegen - function pointer # (instead of forward declaration) or header for function body with "_actual" postfix @@ -1443,7 +1451,7 @@ proc genEnumInfo(m: BModule; typ: PType, name: Rope; info: TLineInfo) = genTypeInfoAux(m, typ, typ, name, info) var nodePtrs = getTempName(m) & "_" & $typ.n.len genTNimNodeArray(m, nodePtrs, rope(typ.n.len)) - var enumNames, specialCases: Rope + var enumNames, specialCases: Rope = "" var firstNimNode = m.typeNodes var hasHoles = false for i in 0.. 1: - var cond: PNode + var cond: PNode = nil for i in 0.. 0: # Ok, we are in a try, lets see which (if any) try's we break out from: for b in countdown(c.blocks.high, i): diff --git a/compiler/docgen.nim b/compiler/docgen.nim index b25a82e4c4..4a0ae6fc9b 100644 --- a/compiler/docgen.nim +++ b/compiler/docgen.nim @@ -170,6 +170,7 @@ proc cmpDecimalsIgnoreCase(a, b: string): int = proc prettyString(a: object): string = # xxx pending std/prettyprint refs https://github.com/nim-lang/RFCs/issues/203#issuecomment-602534906 + result = "" for k, v in fieldPairs(a): result.add k & ": " & $v & "\n" @@ -215,12 +216,16 @@ proc whichType(d: PDoc; n: PNode): PSym = if n.kind == nkSym: if d.types.strTableContains(n.sym): result = n.sym + else: + result = nil else: + result = nil for i in 0.. 0: return @@ -484,7 +492,7 @@ proc externalDep(d: PDoc; module: PSym): string = proc nodeToHighlightedHtml(d: PDoc; n: PNode; result: var string; renderFlags: TRenderFlags = {}; procLink: string) = - var r: TSrcGen + var r: TSrcGen = TSrcGen() var literal = "" initTokRender(r, n, renderFlags) var kind = tkEof @@ -600,7 +608,9 @@ proc runAllExamples(d: PDoc) = rawMessage(d.conf, hintSuccess, ["runnableExamples: " & outp.string]) # removeFile(outp.changeFileExt(ExeExt)) # it's in nimcache, no need to remove -proc quoted(a: string): string = result.addQuoted(a) +proc quoted(a: string): string = + result = "" + result.addQuoted(a) proc toInstantiationInfo(conf: ConfigRef, info: TLineInfo): (string, int, int) = # xxx expose in compiler/lineinfos.nim @@ -726,7 +736,7 @@ proc getAllRunnableExamplesImpl(d: PDoc; n: PNode, dest: var ItemPre, let (rdoccmd, code) = prepareExample(d, n, topLevel) var msg = "Example:" if rdoccmd.len > 0: msg.add " cmd: " & rdoccmd - var s: string + var s: string = "" dispA(d.conf, s, "\n

$1

\n", "\n\n\\textbf{$1}\n", [msg]) dest.add s @@ -942,7 +952,10 @@ proc genDeprecationMsg(d: PDoc, n: PNode): string = if n[1].kind in {nkStrLit..nkTripleStrLit}: result = getConfigVar(d.conf, "doc.deprecationmsg") % [ "label", "Deprecated:", "message", xmltree.escape(n[1].strVal)] + else: + result = "" else: + result = "" doAssert false type DocFlags = enum @@ -950,6 +963,7 @@ type DocFlags = enum kForceExport proc genSeeSrc(d: PDoc, path: string, line: int): string = + result = "" let docItemSeeSrc = getConfigVar(d.conf, "doc.item.seesrc") if docItemSeeSrc.len > 0: let path = relativeTo(AbsoluteFile path, AbsoluteDir getCurrentDir(), '/') @@ -991,7 +1005,7 @@ proc toLangSymbol(k: TSymKind, n: PNode, baseName: string): LangSymbol = result.symKind = k.toHumanStr if k in routineKinds: var - paramTypes: seq[string] + paramTypes: seq[string] = @[] renderParamTypes(paramTypes, n[paramsPos], toNormalize=true) let paramNames = renderParamNames(n[paramsPos], toNormalize=true) # In some rare cases (system.typeof) parameter type is not set for default: @@ -1038,7 +1052,7 @@ proc genItem(d: PDoc, n, nameNode: PNode, k: TSymKind, docFlags: DocFlags, nonEx var result = "" var literal, plainName = "" var kind = tkEof - var comm: ItemPre + var comm: ItemPre = default(ItemPre) if n.kind in routineDefs: getAllRunnableExamples(d, n, comm) else: @@ -1150,7 +1164,7 @@ proc genJsonItem(d: PDoc, n, nameNode: PNode, k: TSymKind, nonExports = false): var name = getNameEsc(d, nameNode) comm = genRecComment(d, n) - r: TSrcGen + r: TSrcGen = default(TSrcGen) renderFlags = {renderNoBody, renderNoComments, renderDocComments, renderExpandUsing} if nonExports: renderFlags.incl renderNonExportedFields @@ -1283,6 +1297,8 @@ proc documentNewEffect(cache: IdentCache; n: PNode): PNode = let s = n[namePos].sym if tfReturnsNew in s.typ.flags: result = newIdentNode(getIdent(cache, "new"), n.info) + else: + result = nil proc documentEffect(cache: IdentCache; n, x: PNode, effectType: TSpecialWord, idx: int): PNode = let spec = effectSpec(x, effectType) @@ -1305,6 +1321,8 @@ proc documentEffect(cache: IdentCache; n, x: PNode, effectType: TSpecialWord, id result = newTreeI(nkExprColonExpr, n.info, newIdentNode(getIdent(cache, $effectType), n.info), effects) + else: + result = nil proc documentWriteEffect(cache: IdentCache; n: PNode; flag: TSymFlag; pragmaName: string): PNode = let s = n[namePos].sym @@ -1318,6 +1336,8 @@ proc documentWriteEffect(cache: IdentCache; n: PNode; flag: TSymFlag; pragmaName if effects.len > 0: result = newTreeI(nkExprColonExpr, n.info, newIdentNode(getIdent(cache, pragmaName), n.info), effects) + else: + result = nil proc documentRaises*(cache: IdentCache; n: PNode) = if n[namePos].kind != nkSym: return @@ -1391,7 +1411,7 @@ proc generateDoc*(d: PDoc, n, orig: PNode, config: ConfigRef, docFlags: DocFlags of nkExportExceptStmt: discard "transformed into nkExportStmt by semExportExcept" of nkFromStmt, nkImportExceptStmt: traceDeps(d, n[0]) of nkCallKinds: - var comm: ItemPre + var comm: ItemPre = default(ItemPre) getAllRunnableExamples(d, n, comm) if comm.len != 0: d.modDescPre.add(comm) else: discard @@ -1500,7 +1520,7 @@ proc finishGenerateDoc*(d: var PDoc) = overloadChoices.sort(cmp) var nameContent = "" for item in overloadChoices: - var itemDesc: string + var itemDesc: string = "" renderItemPre(d, item.descRst, itemDesc) nameContent.add( getConfigVar(d.conf, "doc.item") % ( @@ -1526,7 +1546,7 @@ proc finishGenerateDoc*(d: var PDoc) = for i, entry in d.jEntriesPre: if entry.rst != nil: let resolved = resolveSubs(d.sharedState, entry.rst) - var str: string + var str: string = "" renderRstToOut(d[], resolved, str) entry.json[entry.rstField] = %str d.jEntriesPre[i].rst = nil @@ -1641,7 +1661,7 @@ proc genSection(d: PDoc, kind: TSymKind, groupedToc = false) = for plainName in overloadableNames.sorted(cmpDecimalsIgnoreCase): var overloadChoices = d.tocTable[kind][plainName] overloadChoices.sort(cmp) - var content: string + var content: string = "" for item in overloadChoices: content.add item.content d.toc2[kind].add getConfigVar(d.conf, "doc.section.toc2") % [ @@ -1672,7 +1692,7 @@ proc relLink(outDir: AbsoluteDir, destFile: AbsoluteFile, linkto: RelativeFile): proc genOutFile(d: PDoc, groupedToc = false): string = var - code, content: string + code, content: string = "" title = "" var j = 0 var toc = "" @@ -1781,7 +1801,7 @@ proc writeOutput*(d: PDoc, useWarning = false, groupedToc = false) = proc writeOutputJson*(d: PDoc, useWarning = false) = runAllExamples(d) - var modDesc: string + var modDesc: string = "" for desc in d.modDescFinal: modDesc &= desc let content = %*{"orig": d.filename, @@ -1793,7 +1813,7 @@ proc writeOutputJson*(d: PDoc, useWarning = false) = else: let dir = d.destFile.splitFile.dir createDir(dir) - var f: File + var f: File = default(File) if open(f, d.destFile, fmWrite): write(f, $content) close(f) diff --git a/compiler/docgen2.nim b/compiler/docgen2.nim index 9076034127..7fb11a3bd7 100644 --- a/compiler/docgen2.nim +++ b/compiler/docgen2.nim @@ -39,10 +39,12 @@ template closeImpl(body: untyped) {.dirty.} = discard proc closeDoc*(graph: ModuleGraph; p: PPassContext, n: PNode): PNode = + result = nil closeImpl: writeOutput(g.doc, useWarning, groupedToc) proc closeJson*(graph: ModuleGraph; p: PPassContext, n: PNode): PNode = + result = nil closeImpl: writeOutputJson(g.doc, useWarning) diff --git a/compiler/enumtostr.nim b/compiler/enumtostr.nim index 4ae17235b3..838cd5f971 100644 --- a/compiler/enumtostr.nim +++ b/compiler/enumtostr.nim @@ -56,6 +56,7 @@ proc searchObjCaseImpl(obj: PNode; field: PSym): PNode = if obj.kind == nkRecCase and obj[0].kind == nkSym and obj[0].sym == field: result = obj else: + result = nil for x in obj: result = searchObjCaseImpl(x, field) if result != nil: break diff --git a/compiler/evalffi.nim b/compiler/evalffi.nim index 0112aebb91..3f386f76ec 100644 --- a/compiler/evalffi.nim +++ b/compiler/evalffi.nim @@ -37,9 +37,10 @@ else: var gExeHandle = loadLib() proc getDll(conf: ConfigRef, cache: var TDllCache; dll: string; info: TLineInfo): pointer = + result = nil if dll in cache: return cache[dll] - var libs: seq[string] + var libs: seq[string] = @[] libCandidates(dll, libs) for c in libs: result = loadLib(c) @@ -61,7 +62,7 @@ proc importcSymbol*(conf: ConfigRef, sym: PSym): PNode = let lib = sym.annex if lib != nil and lib.path.kind notin {nkStrLit..nkTripleStrLit}: globalError(conf, sym.info, "dynlib needs to be a string lit") - var theAddr: pointer + var theAddr: pointer = nil if (lib.isNil or lib.kind == libHeader) and not gExeHandle.isNil: libPathMsg = "current exe: " & getAppFilename() & " nor libc: " & libcDll # first try this exe itself: @@ -108,6 +109,7 @@ proc mapCallConv(conf: ConfigRef, cc: TCallingConvention, info: TLineInfo): TABI of ccStdCall: result = when defined(windows) and defined(x86): STDCALL else: DEFAULT_ABI of ccCDecl: result = DEFAULT_ABI else: + result = default(TABI) globalError(conf, info, "cannot map calling convention to FFI") template rd(typ, p: untyped): untyped = (cast[ptr typ](p))[] @@ -132,6 +134,8 @@ proc packSize(conf: ConfigRef, v: PNode, typ: PType): int = result = sizeof(pointer) elif v.len != 0: result = v.len * packSize(conf, v[0], typ[1]) + else: + result = 0 else: result = getSize(conf, typ).int @@ -140,6 +144,7 @@ proc pack(conf: ConfigRef, v: PNode, typ: PType, res: pointer) proc getField(conf: ConfigRef, n: PNode; position: int): PSym = case n.kind of nkRecList: + result = nil for i in 0..= 5 else: @@ -644,7 +648,7 @@ proc externalFileChanged(conf: ConfigRef; cfile: Cfile): bool = let hashFile = toGeneratedFile(conf, conf.mangleModuleName(cfile.cname).AbsoluteFile, "sha1") let currentHash = footprint(conf, cfile) - var f: File + var f: File = default(File) if open(f, hashFile.string, fmRead): let oldHash = parseSecureHash(f.readLine()) close(f) @@ -779,6 +783,7 @@ template tryExceptOSErrorMessage(conf: ConfigRef; errorPrefix: string = "", body raise proc getExtraCmds(conf: ConfigRef; output: AbsoluteFile): seq[string] = + result = @[] when defined(macosx): if optCDebug in conf.globalOptions and optGenStaticLib notin conf.globalOptions: # if needed, add an option to skip or override location @@ -861,6 +866,7 @@ proc hcrLinkTargetName(conf: ConfigRef, objFile: string, isMain = false): Absolu result = conf.getNimcacheDir / RelativeFile(targetName) proc displayProgressCC(conf: ConfigRef, path, compileCmd: string): string = + result = "" if conf.hasHint(hintCC): if optListCmd in conf.globalOptions or conf.verbosity > 1: result = MsgKindToStr[hintCC] % (demangleModuleName(path.splitFile.name) & ": " & compileCmd) @@ -883,15 +889,15 @@ proc preventLinkCmdMaxCmdLen(conf: ConfigRef, linkCmd: string) = proc callCCompiler*(conf: ConfigRef) = var - linkCmd: string + linkCmd: string = "" extraCmds: seq[string] if conf.globalOptions * {optCompileOnly, optGenScript} == {optCompileOnly}: return # speed up that call if only compiling and no script shall be # generated #var c = cCompiler var script: Rope = "" - var cmds: TStringSeq - var prettyCmds: TStringSeq + var cmds: TStringSeq = default(TStringSeq) + var prettyCmds: TStringSeq = default(TStringSeq) let prettyCb = proc (idx: int) = writePrettyCmdsStderr(prettyCmds[idx]) for idx, it in conf.toCompile: @@ -1022,8 +1028,9 @@ proc writeJsonBuildInstructions*(conf: ConfigRef) = conf.jsonBuildFile.string.writeFile(bcache.toJson.pretty) proc changeDetectedViaJsonBuildInstructions*(conf: ConfigRef; jsonFile: AbsoluteFile): bool = + result = false if not fileExists(jsonFile) or not fileExists(conf.absOutFile): return true - var bcache: BuildCache + var bcache: BuildCache = default(BuildCache) try: bcache.fromJson(jsonFile.string.parseFile) except IOError, OSError, ValueError: stderr.write "Warning: JSON processing failed for: $#\n" % jsonFile.string @@ -1039,7 +1046,7 @@ proc changeDetectedViaJsonBuildInstructions*(conf: ConfigRef; jsonFile: Absolute if $secureHashFile(file) != hash: return true proc runJsonBuildInstructions*(conf: ConfigRef; jsonFile: AbsoluteFile) = - var bcache: BuildCache + var bcache: BuildCache = default(BuildCache) try: bcache.fromJson(jsonFile.string.parseFile) except ValueError, KeyError, JsonKindError: let e = getCurrentException() @@ -1052,7 +1059,8 @@ proc runJsonBuildInstructions*(conf: ConfigRef; jsonFile: AbsoluteFile) = globalError(conf, gCmdLineInfo, "jsonscript command outputFile '$1' must match '$2' which was specified during --compileOnly, see \"outputFile\" entry in '$3' " % [outputCurrent, output, jsonFile.string]) - var cmds, prettyCmds: TStringSeq + var cmds: TStringSeq = default(TStringSeq) + var prettyCmds: TStringSeq= default(TStringSeq) let prettyCb = proc (idx: int) = writePrettyCmdsStderr(prettyCmds[idx]) for (name, cmd) in bcache.compile: cmds.add cmd @@ -1062,6 +1070,7 @@ proc runJsonBuildInstructions*(conf: ConfigRef; jsonFile: AbsoluteFile) = for cmd in bcache.extraCmds: execExternalProgram(conf, cmd, hintExecuting) proc genMappingFiles(conf: ConfigRef; list: CfileList): Rope = + result = "" for it in list: result.addf("--file:r\"$1\"$N", [rope(it.cname.string)]) diff --git a/compiler/filters.nim b/compiler/filters.nim index 8151c0b938..8d8af6b1c8 100644 --- a/compiler/filters.nim +++ b/compiler/filters.nim @@ -29,23 +29,30 @@ proc getArg(conf: ConfigRef; n: PNode, name: string, pos: int): PNode = return n[i] proc charArg*(conf: ConfigRef; n: PNode, name: string, pos: int, default: char): char = + var x = getArg(conf, n, name, pos) if x == nil: result = default elif x.kind == nkCharLit: result = chr(int(x.intVal)) - else: invalidPragma(conf, n) + else: + result = default(char) + invalidPragma(conf, n) proc strArg*(conf: ConfigRef; n: PNode, name: string, pos: int, default: string): string = var x = getArg(conf, n, name, pos) if x == nil: result = default elif x.kind in {nkStrLit..nkTripleStrLit}: result = x.strVal - else: invalidPragma(conf, n) + else: + result = "" + invalidPragma(conf, n) proc boolArg*(conf: ConfigRef; n: PNode, name: string, pos: int, default: bool): bool = var x = getArg(conf, n, name, pos) if x == nil: result = default elif x.kind == nkIdent and cmpIgnoreStyle(x.ident.s, "true") == 0: result = true elif x.kind == nkIdent and cmpIgnoreStyle(x.ident.s, "false") == 0: result = false - else: invalidPragma(conf, n) + else: + result = false + invalidPragma(conf, n) proc filterStrip*(conf: ConfigRef; stdin: PLLStream, filename: AbsoluteFile, call: PNode): PLLStream = var pattern = strArg(conf, call, "startswith", 1, "") diff --git a/compiler/gorgeimpl.nim b/compiler/gorgeimpl.nim index 558a6c9a3d..fb0fafc985 100644 --- a/compiler/gorgeimpl.nim +++ b/compiler/gorgeimpl.nim @@ -29,10 +29,11 @@ proc readOutput(p: Process): (string, int) = proc opGorge*(cmd, input, cache: string, info: TLineInfo; conf: ConfigRef): (string, int) = let workingDir = parentDir(toFullPath(conf, info)) + result = ("", 0) if cache.len > 0: let h = secureHash(cmd & "\t" & input & "\t" & cache) let filename = toGeneratedFile(conf, AbsoluteFile("gorge_" & $h), "txt").string - var f: File + var f: File = default(File) if optForceFullMake notin conf.globalOptions and open(f, filename): result = (f.readAll, 0) f.close diff --git a/compiler/guards.nim b/compiler/guards.nim index 15c6a64e36..1366a2382c 100644 --- a/compiler/guards.nim +++ b/compiler/guards.nim @@ -51,6 +51,10 @@ proc isLet(n: PNode): bool = elif n.sym.kind == skParam and skipTypes(n.sym.typ, abstractInst).kind notin {tyVar}: result = true + else: + result = false + else: + result = false proc isVar(n: PNode): bool = n.kind == nkSym and n.sym.kind in {skResult, skVar} and @@ -136,6 +140,8 @@ proc neg(n: PNode; o: Operators): PNode = result = a elif b != nil: result = b + else: + result = nil else: # leave not (a == 4) as it is result = newNodeI(nkCall, n.info, 2) @@ -330,6 +336,8 @@ proc usefulFact(n: PNode; o: Operators): PNode = result = n elif n[1].getMagic in someLen or n[2].getMagic in someLen: result = n + else: + result = nil of someLe+someLt: if isLetLocation(n[1], true) or isLetLocation(n[2], true): # XXX algebraic simplifications! 'i-1 < a.len' --> 'i < a.len+1' @@ -337,12 +345,18 @@ proc usefulFact(n: PNode; o: Operators): PNode = elif n[1].getMagic in someLen or n[2].getMagic in someLen: # XXX Rethink this whole idea of 'usefulFact' for semparallel result = n + else: + result = nil of mIsNil: if isLetLocation(n[1], false) or isVar(n[1]): result = n + else: + result = nil of someIn: if isLetLocation(n[1], true): result = n + else: + result = nil of mAnd: let a = usefulFact(n[1], o) @@ -356,10 +370,14 @@ proc usefulFact(n: PNode; o: Operators): PNode = result = a elif b != nil: result = b + else: + result = nil of mNot: let a = usefulFact(n[1], o) if a != nil: result = a.neg(o) + else: + result = nil of mOr: # 'or' sucks! (p.isNil or q.isNil) --> hard to do anything # with that knowledge... @@ -376,6 +394,8 @@ proc usefulFact(n: PNode; o: Operators): PNode = result[1] = a result[2] = b result = result.neg(o) + else: + result = nil elif n.kind == nkSym and n.sym.kind == skLet: # consider: # let a = 2 < x @@ -384,8 +404,12 @@ proc usefulFact(n: PNode; o: Operators): PNode = # We make can easily replace 'a' by '2 < x' here: if n.sym.astdef != nil: result = usefulFact(n.sym.astdef, o) + else: + result = nil elif n.kind == nkStmtListExpr: result = usefulFact(n.lastSon, o) + else: + result = nil type TModel* = object @@ -451,8 +475,9 @@ proc hasSubTree(n, x: PNode): bool = of nkEmpty..nkNilLit: result = n.sameTree(x) of nkFormalParams: - discard + result = false else: + result = false for i in 0.. unknown! if sameTree(fact[2], eq[val]): result = impYes elif valuesUnequal(fact[2], eq[val]): result = impNo + else: + result = impUnknown elif sameTree(fact[2], eq[loc]): if sameTree(fact[1], eq[val]): result = impYes elif valuesUnequal(fact[1], eq[val]): result = impNo + else: + result = impUnknown + else: + result = impUnknown of mInSet: # remember: mInSet is 'contains' so the set comes first! if sameTree(fact[2], eq[loc]) and isValue(eq[val]): if inSet(fact[1], eq[val]): result = impYes else: result = impNo - of mNot, mOr, mAnd: assert(false, "impliesEq") - else: discard + else: + result = impUnknown + of mNot, mOr, mAnd: + result = impUnknown + assert(false, "impliesEq") + else: result = impUnknown proc leImpliesIn(x, c, aSet: PNode): TImplication = if c.kind in {nkCharLit..nkUInt64Lit}: @@ -512,13 +549,19 @@ proc leImpliesIn(x, c, aSet: PNode): TImplication = var value = newIntNode(c.kind, firstOrd(nil, x.typ)) # don't iterate too often: if c.intVal - value.intVal < 1000: - var i, pos, neg: int + var i, pos, neg: int = 0 while value.intVal <= c.intVal: if inSet(aSet, value): inc pos else: inc neg inc i; inc value.intVal if pos == i: result = impYes elif neg == i: result = impNo + else: + result = impUnknown + else: + result = impUnknown + else: + result = impUnknown proc geImpliesIn(x, c, aSet: PNode): TImplication = if c.kind in {nkCharLit..nkUInt64Lit}: @@ -529,17 +572,23 @@ proc geImpliesIn(x, c, aSet: PNode): TImplication = let max = lastOrd(nil, x.typ) # don't iterate too often: if max - getInt(value) < toInt128(1000): - var i, pos, neg: int + var i, pos, neg: int = 0 while value.intVal <= max: if inSet(aSet, value): inc pos else: inc neg inc i; inc value.intVal if pos == i: result = impYes elif neg == i: result = impNo + else: result = impUnknown + else: + result = impUnknown + else: + result = impUnknown proc compareSets(a, b: PNode): TImplication = if equalSets(nil, a, b): result = impYes elif intersectSets(nil, a, b).len == 0: result = impNo + else: result = impUnknown proc impliesIn(fact, loc, aSet: PNode): TImplication = case fact[0].sym.magic @@ -550,22 +599,32 @@ proc impliesIn(fact, loc, aSet: PNode): TImplication = elif sameTree(fact[2], loc): if inSet(aSet, fact[1]): result = impYes else: result = impNo + else: + result = impUnknown of mInSet: if sameTree(fact[2], loc): result = compareSets(fact[1], aSet) + else: + result = impUnknown of someLe: if sameTree(fact[1], loc): result = leImpliesIn(fact[1], fact[2], aSet) elif sameTree(fact[2], loc): result = geImpliesIn(fact[2], fact[1], aSet) + else: + result = impUnknown of someLt: if sameTree(fact[1], loc): result = leImpliesIn(fact[1], fact[2].pred, aSet) elif sameTree(fact[2], loc): # 4 < x --> 3 <= x result = geImpliesIn(fact[2], fact[1].pred, aSet) - of mNot, mOr, mAnd: assert(false, "impliesIn") - else: discard + else: + result = impUnknown + of mNot, mOr, mAnd: + result = impUnknown + assert(false, "impliesIn") + else: result = impUnknown proc valueIsNil(n: PNode): TImplication = if n.kind == nkNilLit: impYes @@ -577,13 +636,19 @@ proc impliesIsNil(fact, eq: PNode): TImplication = of mIsNil: if sameTree(fact[1], eq[1]): result = impYes + else: + result = impUnknown of someEq: if sameTree(fact[1], eq[1]): result = valueIsNil(fact[2].skipConv) elif sameTree(fact[2], eq[1]): result = valueIsNil(fact[1].skipConv) - of mNot, mOr, mAnd: assert(false, "impliesIsNil") - else: discard + else: + result = impUnknown + of mNot, mOr, mAnd: + result = impUnknown + assert(false, "impliesIsNil") + else: result = impUnknown proc impliesGe(fact, x, c: PNode): TImplication = assert isLocation(x) @@ -594,32 +659,57 @@ proc impliesGe(fact, x, c: PNode): TImplication = # fact: x = 4; question x >= 56? --> true iff 4 >= 56 if leValue(c, fact[2]): result = impYes else: result = impNo + else: + result = impUnknown elif sameTree(fact[2], x): if isValue(fact[1]) and isValue(c): if leValue(c, fact[1]): result = impYes else: result = impNo + else: + result = impUnknown + else: + result = impUnknown of someLt: if sameTree(fact[1], x): if isValue(fact[2]) and isValue(c): # fact: x < 4; question N <= x? --> false iff N <= 4 if leValue(fact[2], c): result = impNo + else: result = impUnknown # fact: x < 4; question 2 <= x? --> we don't know + else: + result = impUnknown elif sameTree(fact[2], x): # fact: 3 < x; question: N-1 < x ? --> true iff N-1 <= 3 if isValue(fact[1]) and isValue(c): if leValue(c.pred, fact[1]): result = impYes + else: result = impUnknown + else: + result = impUnknown + else: + result = impUnknown of someLe: if sameTree(fact[1], x): if isValue(fact[2]) and isValue(c): # fact: x <= 4; question x >= 56? --> false iff 4 <= 56 if leValue(fact[2], c): result = impNo # fact: x <= 4; question x >= 2? --> we don't know + else: + result = impUnknown + else: + result = impUnknown elif sameTree(fact[2], x): # fact: 3 <= x; question: x >= 2 ? --> true iff 2 <= 3 if isValue(fact[1]) and isValue(c): if leValue(c, fact[1]): result = impYes - of mNot, mOr, mAnd: assert(false, "impliesGe") - else: discard + else: result = impUnknown + else: + result = impUnknown + else: + result = impUnknown + of mNot, mOr, mAnd: + result = impUnknown + assert(false, "impliesGe") + else: result = impUnknown proc impliesLe(fact, x, c: PNode): TImplication = if not isLocation(x): @@ -634,35 +724,59 @@ proc impliesLe(fact, x, c: PNode): TImplication = # fact: x = 4; question x <= 56? --> true iff 4 <= 56 if leValue(fact[2], c): result = impYes else: result = impNo + else: + result = impUnknown elif sameTree(fact[2], x): if isValue(fact[1]) and isValue(c): if leValue(fact[1], c): result = impYes else: result = impNo + else: + result = impUnknown + else: + result = impUnknown of someLt: if sameTree(fact[1], x): if isValue(fact[2]) and isValue(c): # fact: x < 4; question x <= N? --> true iff N-1 <= 4 if leValue(fact[2], c.pred): result = impYes + else: + result = impUnknown # fact: x < 4; question x <= 2? --> we don't know + else: + result = impUnknown elif sameTree(fact[2], x): # fact: 3 < x; question: x <= 1 ? --> false iff 1 <= 3 if isValue(fact[1]) and isValue(c): if leValue(c, fact[1]): result = impNo - + else: result = impUnknown + else: + result = impUnknown + else: + result = impUnknown of someLe: if sameTree(fact[1], x): if isValue(fact[2]) and isValue(c): # fact: x <= 4; question x <= 56? --> true iff 4 <= 56 if leValue(fact[2], c): result = impYes + else: result = impUnknown # fact: x <= 4; question x <= 2? --> we don't know + else: + result = impUnknown elif sameTree(fact[2], x): # fact: 3 <= x; question: x <= 2 ? --> false iff 2 < 3 if isValue(fact[1]) and isValue(c): if leValue(c, fact[1].pred): result = impNo + else:result = impUnknown + else: + result = impUnknown + else: + result = impUnknown - of mNot, mOr, mAnd: assert(false, "impliesLe") - else: discard + of mNot, mOr, mAnd: + result = impUnknown + assert(false, "impliesLe") + else: result = impUnknown proc impliesLt(fact, x, c: PNode): TImplication = # x < 3 same as x <= 2: @@ -674,6 +788,8 @@ proc impliesLt(fact, x, c: PNode): TImplication = let q = x.pred if q != x: result = impliesLe(fact, q, c) + else: + result = impUnknown proc `~`(x: TImplication): TImplication = case x @@ -725,6 +841,7 @@ proc factImplies(fact, prop: PNode): TImplication = proc doesImply*(facts: TModel, prop: PNode): TImplication = assert prop.kind in nkCallKinds + result = impUnknown for f in facts.s: # facts can be invalidated, in which case they are 'nil': if not f.isNil: @@ -900,6 +1017,7 @@ proc applyReplacements(n: PNode; rep: TReplacements): PNode = proc pleViaModelRec(m: var TModel; a, b: PNode): TImplication = # now check for inferrable facts: a <= b and b <= c implies a <= c + result = impUnknown for i in 0..m.s.high: let fact = m.s[i] if fact != nil and fact.getMagic in someLe: @@ -981,7 +1099,7 @@ proc addFactLt*(m: var TModel; a, b: PNode) = proc settype(n: PNode): PType = result = newType(tySet, ItemId(module: -1, item: -1), n.typ.owner) - var idgen: IdGenerator + var idgen: IdGenerator = nil addSonSkipIntLit(result, n.typ, idgen) proc buildOf(it, loc: PNode; o: Operators): PNode = diff --git a/compiler/hlo.nim b/compiler/hlo.nim index 2e1652f09d..744fddcc0f 100644 --- a/compiler/hlo.nim +++ b/compiler/hlo.nim @@ -20,9 +20,11 @@ proc evalPattern(c: PContext, n, orig: PNode): PNode = # we need to ensure that the resulting AST is semchecked. However, it's # awful to semcheck before macro invocation, so we don't and treat # templates and macros as immediate in this context. - var rule: string - if c.config.hasHint(hintPattern): - rule = renderTree(n, {renderNoComments}) + var rule: string = + if c.config.hasHint(hintPattern): + renderTree(n, {renderNoComments}) + else: + "" let s = n[0].sym case s.kind of skMacro: diff --git a/compiler/ic/cbackend.nim b/compiler/ic/cbackend.nim index 21f69e4852..a1922c812d 100644 --- a/compiler/ic/cbackend.nim +++ b/compiler/ic/cbackend.nim @@ -101,7 +101,7 @@ proc aliveSymsChanged(config: ConfigRef; position: int; alive: AliveSyms): bool var f2 = rodfiles.open(asymFile.string) f2.loadHeader() f2.loadSection aliveSymsSection - var oldData: seq[int32] + var oldData: seq[int32] = @[] f2.loadSeq(oldData) f2.close if f2.err == ok and oldData == s: diff --git a/compiler/ic/dce.nim b/compiler/ic/dce.nim index bc61a38dec..ce64221010 100644 --- a/compiler/ic/dce.nim +++ b/compiler/ic/dce.nim @@ -40,10 +40,14 @@ proc isExportedToC(c: var AliveContext; g: PackedModuleGraph; symId: int32): boo if ({sfExportc, sfCompilerProc} * flags != {}) or (symPtr.kind == skMethod): result = true + else: + result = false # XXX: This used to be a condition to: # (sfExportc in prc.flags and lfExportLib in prc.loc.flags) or if sfCompilerProc in flags: c.compilerProcs[g[c.thisModule].fromDisk.strings[symPtr.name]] = (c.thisModule, symId) + else: + result = false template isNotGeneric(n: NodePos): bool = ithSon(tree, n, genericParamsPos).kind == nkEmpty diff --git a/compiler/ic/ic.nim b/compiler/ic/ic.nim index a72db57c5f..c2f3f793c3 100644 --- a/compiler/ic/ic.nim +++ b/compiler/ic/ic.nim @@ -813,6 +813,7 @@ proc loadProcHeader(c: var PackedDecoder; g: var PackedModuleGraph; thisModule: proc loadProcBody(c: var PackedDecoder; g: var PackedModuleGraph; thisModule: int; tree: PackedTree; n: NodePos): PNode = + result = nil var i = 0 for n0 in sonsReadonly(tree, n): if i == bodyPos: @@ -1147,6 +1148,8 @@ proc initRodIter*(it: var RodIter; config: ConfigRef, cache: IdentCache; if it.i < it.values.len: result = loadSym(it.decoder, g, int(module), it.values[it.i]) inc it.i + else: + result = nil proc initRodIterAllSyms*(it: var RodIter; config: ConfigRef, cache: IdentCache; g: var PackedModuleGraph; module: FileIndex, importHidden: bool): PSym = @@ -1164,11 +1167,15 @@ proc initRodIterAllSyms*(it: var RodIter; config: ConfigRef, cache: IdentCache; if it.i < it.values.len: result = loadSym(it.decoder, g, int(module), it.values[it.i]) inc it.i + else: + result = nil proc nextRodIter*(it: var RodIter; g: var PackedModuleGraph): PSym = if it.i < it.values.len: result = loadSym(it.decoder, g, it.module, it.values[it.i]) inc it.i + else: + result = nil iterator interfaceSymbols*(config: ConfigRef, cache: IdentCache; g: var PackedModuleGraph; module: FileIndex; @@ -1201,7 +1208,7 @@ proc searchForCompilerproc*(m: LoadedModule; name: string): int32 = # ------------------------- .rod file viewer --------------------------------- proc rodViewer*(rodfile: AbsoluteFile; config: ConfigRef, cache: IdentCache) = - var m: PackedModule + var m: PackedModule = PackedModule() let err = loadRodFile(rodfile, m, config, ignoreConfig=true) if err != ok: config.quitOrRaise "Error: could not load: " & $rodfile.string & " reason: " & $err diff --git a/compiler/ic/navigator.nim b/compiler/ic/navigator.nim index cbba591c5a..ab49b3b7a1 100644 --- a/compiler/ic/navigator.nim +++ b/compiler/ic/navigator.nim @@ -34,7 +34,11 @@ proc isTracked(current, trackPos: PackedLineInfo, tokenLen: int): bool = if current.file == trackPos.file and current.line == trackPos.line: let col = trackPos.col if col >= current.col and col < current.col+tokenLen: - return true + result = true + else: + result = false + else: + result = false proc searchLocalSym(c: var NavContext; s: PackedSym; info: PackedLineInfo): bool = result = s.name != LitId(0) and diff --git a/compiler/ic/packed_ast.nim b/compiler/ic/packed_ast.nim index 0bf5cd4c31..8eafa5e968 100644 --- a/compiler/ic/packed_ast.nim +++ b/compiler/ic/packed_ast.nim @@ -305,6 +305,7 @@ proc sons3*(tree: PackedTree; n: NodePos): (NodePos, NodePos, NodePos) = result = (NodePos a, NodePos b, NodePos c) proc ithSon*(tree: PackedTree; n: NodePos; i: int): NodePos = + result = default(NodePos) if tree.nodes[n.int].kind > nkNilLit: var count = 0 for child in sonsReadonly(tree, n): diff --git a/compiler/ic/rodfiles.nim b/compiler/ic/rodfiles.nim index e492624d04..41e85084f1 100644 --- a/compiler/ic/rodfiles.nim +++ b/compiler/ic/rodfiles.nim @@ -215,7 +215,7 @@ proc storeHeader*(f: var RodFile) = proc loadHeader*(f: var RodFile) = ## Loads the header which is described by `cookie`. if f.err != ok: return - var thisCookie: array[cookie.len, byte] + var thisCookie: array[cookie.len, byte] = default(array[cookie.len, byte]) if f.f.readBytes(thisCookie, 0, thisCookie.len) != thisCookie.len: setError f, ioFailure elif thisCookie != cookie: @@ -231,13 +231,14 @@ proc storeSection*(f: var RodFile; s: RodSection) = proc loadSection*(f: var RodFile; expected: RodSection) = ## read the bytes value of s, sets and error if the section is incorrect. if f.err != ok: return - var s: RodSection + var s: RodSection = default(RodSection) loadPrim(f, s) if expected != s and f.err == ok: setError f, wrongSection proc create*(filename: string): RodFile = ## create the file and open it for writing + result = default(RodFile) if not open(result.f, filename, fmWrite): setError result, cannotOpen @@ -245,5 +246,6 @@ proc close*(f: var RodFile) = close(f.f) proc open*(filename: string): RodFile = ## open the file for reading + result = default(RodFile) if not open(result.f, filename, fmRead): setError result, cannotOpen diff --git a/compiler/importer.nim b/compiler/importer.nim index 54489ada4e..f5eb5329d9 100644 --- a/compiler/importer.nim +++ b/compiler/importer.nim @@ -113,6 +113,7 @@ proc rawImportSymbol(c: PContext, s, origin: PSym; importSet: var IntSet) = proc splitPragmas(c: PContext, n: PNode): (PNode, seq[TSpecialWord]) = template bail = globalError(c.config, n.info, "invalid pragma") + result = (nil, @[]) if n.kind == nkPragmaExpr: if n.len == 2 and n[1].kind == nkPragma: result[0] = n[0] @@ -307,6 +308,8 @@ proc myImportModule(c: PContext, n: var PNode, importStmtResult: PNode): PSym = suggestSym(c.graph, n.info, result, c.graph.usageSym, false) importStmtResult.add newSymNode(result, n.info) #newStrNode(toFullPath(c.config, f), n.info) + else: + result = nil proc afterImport(c: PContext, m: PSym) = # fixes bug #17510, for re-exported symbols diff --git a/compiler/injectdestructors.nim b/compiler/injectdestructors.nim index 4463d1d694..aa6470d349 100644 --- a/compiler/injectdestructors.nim +++ b/compiler/injectdestructors.nim @@ -432,6 +432,7 @@ proc destructiveMoveVar(n: PNode; c: var Con; s: var Scope): PNode = proc isCapturedVar(n: PNode): bool = let root = getRoot(n) if root != nil: result = root.name.s[0] == ':' + else: result = false proc passCopyToSink(n: PNode; c: var Con; s: var Scope): PNode = result = newNodeIT(nkStmtListExpr, n.info, n.typ) @@ -733,7 +734,9 @@ template handleNestedTempl(n, processCall: untyped, willProduceStmt = false, result[^1] = maybeVoid(n[^1], s) dec c.inUncheckedAssignSection, inUncheckedAssignSection - else: assert(false) + else: + result = nil + assert(false) proc pRaiseStmt(n: PNode, c: var Con; s: var Scope): PNode = if optOwnedRefs in c.graph.config.globalOptions and n[0].kind != nkEmpty: @@ -1042,6 +1045,7 @@ proc p(n: PNode; c: var Con; s: var Scope; mode: ProcessMode; tmpFlags = {sfSing of nkGotoState, nkState, nkAsmStmt: result = n else: + result = nil internalError(c.graph.config, n.info, "cannot inject destructors to node kind: " & $n.kind) proc sameLocation*(a, b: PNode): bool = diff --git a/compiler/int128.nim b/compiler/int128.nim index b0341eb379..6968b1f892 100644 --- a/compiler/int128.nim +++ b/compiler/int128.nim @@ -171,6 +171,7 @@ proc addToHex*(result: var string; arg: Int128) = i -= 1 proc toHex*(arg: Int128): string = + result = "" result.addToHex(arg) proc inc*(a: var Int128, y: uint32 = 1) = @@ -330,8 +331,8 @@ proc `*`*(a: Int128, b: int32): Int128 = if b < 0: result = -result -proc `*=`*(a: var Int128, b: int32): Int128 = - result = result * b +proc `*=`(a: var Int128, b: int32) = + a = a * b proc makeInt128(high, low: uint64): Int128 = result.udata[0] = cast[uint32](low) @@ -360,6 +361,7 @@ proc `*=`*(a: var Int128, b: Int128) = import bitops proc fastLog2*(a: Int128): int = + result = 0 if a.udata[3] != 0: return 96 + fastLog2(a.udata[3]) if a.udata[2] != 0: diff --git a/compiler/isolation_check.nim b/compiler/isolation_check.nim index 273bfb7f9f..5fd1b8d51b 100644 --- a/compiler/isolation_check.nim +++ b/compiler/isolation_check.nim @@ -21,6 +21,7 @@ proc canAlias(arg, ret: PType; marker: var IntSet): bool proc canAliasN(arg: PType; n: PNode; marker: var IntSet): bool = case n.kind of nkRecList: + result = false for i in 0.. 2: @@ -833,7 +837,7 @@ proc arith(p: PProc, n: PNode, r: var TCompRes, op: TMagic) = if mapType(n[1].typ) != etyBaseIndex: arithAux(p, n, r, op) else: - var x, y: TCompRes + var x, y: TCompRes = default(TCompRes) gen(p, n[1], x) gen(p, n[2], y) r.res = "($# == $# && $# == $#)" % [x.address, y.address, x.res, y.res] @@ -866,7 +870,7 @@ proc genLineDir(p: PProc, n: PNode) = p.previousFileName = currentFileName proc genWhileStmt(p: PProc, n: PNode) = - var cond: TCompRes + var cond: TCompRes = default(TCompRes) internalAssert p.config, isEmptyType(n.typ) genLineDir(p, n) inc(p.unique) @@ -961,6 +965,7 @@ proc genTry(p: PProc, n: PNode, r: var TCompRes) = elif it.kind == nkType: throwObj = it else: + throwObj = nil internalError(p.config, n.info, "genTryStmt") if orExpr != "": orExpr.add("||") @@ -1001,7 +1006,7 @@ proc genTry(p: PProc, n: PNode, r: var TCompRes) = proc genRaiseStmt(p: PProc, n: PNode) = if n[0].kind != nkEmpty: - var a: TCompRes + var a: TCompRes = default(TCompRes) gen(p, n[0], a) let typ = skipTypes(n[0].typ, abstractPtrs) genLineDir(p, n) @@ -1015,7 +1020,7 @@ proc genRaiseStmt(p: PProc, n: PNode) = proc genCaseJS(p: PProc, n: PNode, r: var TCompRes) = var - a, b, cond, stmt: TCompRes + a, b, cond, stmt: TCompRes = default(TCompRes) genLineDir(p, n) gen(p, n[0], cond) let typeKind = skipTypes(n[0].typ, abstractVar).kind @@ -1149,7 +1154,7 @@ proc genAsmOrEmitStmt(p: PProc, n: PNode) = if false: discard else: - var r: TCompRes + var r = default(TCompRes) gen(p, it, r) if it.typ.kind == tyPointer: @@ -1165,13 +1170,13 @@ proc genAsmOrEmitStmt(p: PProc, n: PNode) = p.body.add(r.rdLoc) else: - var r: TCompRes + var r: TCompRes = default(TCompRes) gen(p, it, r) p.body.add(r.rdLoc) p.body.add "\L" proc genIf(p: PProc, n: PNode, r: var TCompRes) = - var cond, stmt: TCompRes + var cond, stmt: TCompRes = default(TCompRes) var toClose = 0 if not isEmptyType(n.typ): r.kind = resVal @@ -1208,6 +1213,7 @@ proc generateHeader(p: PProc, typ: PType): Rope = result.add("_Idx") proc countJsParams(typ: PType): int = + result = 0 for i in 1..= 3: # echo "BEGIN generating code for: " & prc.name.s var p = newProc(oldProc.g, oldProc.module, prc.ast, prc.options) @@ -2765,7 +2774,7 @@ proc genProc(oldProc: PProc, prc: PSym): Rope = # echo "END generated code for: " & prc.name.s proc genStmt(p: PProc, n: PNode) = - var r: TCompRes + var r: TCompRes = default(TCompRes) gen(p, n, r) if r.res != "": lineF(p, "$#;$n", [r.res]) diff --git a/compiler/lambdalifting.nim b/compiler/lambdalifting.nim index ce36123b3a..ac4c160f93 100644 --- a/compiler/lambdalifting.nim +++ b/compiler/lambdalifting.nim @@ -187,6 +187,8 @@ proc getEnvParam*(routine: PSym): PSym = if hidden.kind == nkSym and hidden.sym.name.s == paramName: result = hidden.sym assert sfFromGeneric in result.flags + else: + result = nil proc interestingVar(s: PSym): bool {.inline.} = result = s.kind in {skVar, skLet, skTemp, skForVar, skParam, skResult} and @@ -199,6 +201,8 @@ proc illegalCapture(s: PSym): bool {.inline.} = proc isInnerProc(s: PSym): bool = if s.kind in {skProc, skFunc, skMethod, skConverter, skIterator} and s.magic == mNone: result = s.skipGenericOwner.kind in routineKinds + else: + result = false proc newAsgnStmt(le, ri: PNode, info: TLineInfo): PNode = # Bugfix: unfortunately we cannot use 'nkFastAsgn' here as that would @@ -711,6 +715,7 @@ proc symToClosure(n: PNode; owner: PSym; d: var DetectionPass; # direct dependency, so use the outer's env variable: result = makeClosure(d.graph, d.idgen, s, setupEnvVar(owner, d, c, n.info), n.info) else: + result = nil let available = getHiddenParam(d.graph, owner) let wanted = getHiddenParam(d.graph, s).typ # ugh: call through some other inner proc; @@ -936,7 +941,7 @@ proc liftForLoop*(g: ModuleGraph; body: PNode; idgen: IdGenerator; owner: PSym): result = newNodeI(nkStmtList, body.info) # static binding? - var env: PSym + var env: PSym = nil let op = call[0] if op.kind == nkSym and op.sym.isIterator: # createClosure() diff --git a/compiler/lexer.nim b/compiler/lexer.nim index 5962c8b9bb..93a5f80406 100644 --- a/compiler/lexer.nim +++ b/compiler/lexer.nim @@ -148,9 +148,11 @@ proc isNimIdentifier*(s: string): bool = var i = 1 while i < sLen: if s[i] == '_': inc(i) - if i < sLen and s[i] notin SymChars: return + if i < sLen and s[i] notin SymChars: return false inc(i) result = true + else: + result = false proc `$`*(tok: Token): string = case tok.tokType @@ -537,8 +539,8 @@ proc getNumber(L: var Lexer, result: var Token) = of floatTypes: result.fNumber = parseFloat(result.literal) of tkUInt64Lit, tkUIntLit: - var iNumber: uint64 - var len: int + var iNumber: uint64 = uint64(0) + var len: int = 0 try: len = parseBiggestUInt(result.literal, iNumber) except ValueError: @@ -547,8 +549,8 @@ proc getNumber(L: var Lexer, result: var Token) = raise newException(ValueError, "invalid integer: " & result.literal) result.iNumber = cast[int64](iNumber) else: - var iNumber: int64 - var len: int + var iNumber: int64 = int64(0) + var len: int = 0 try: len = parseBiggestInt(result.literal, iNumber) except ValueError: @@ -1007,6 +1009,7 @@ proc getPrecedence*(tok: Token): int = else: return -10 proc newlineFollows*(L: Lexer): bool = + result = false var pos = L.bufpos while true: case L.buf[pos] @@ -1394,8 +1397,9 @@ proc rawGetTok*(L: var Lexer, tok: var Token) = proc getIndentWidth*(fileIdx: FileIndex, inputstream: PLLStream; cache: IdentCache; config: ConfigRef): int = - var lex: Lexer - var tok: Token + result = 0 + var lex: Lexer = default(Lexer) + var tok: Token = default(Token) initToken(tok) openLexer(lex, fileIdx, inputstream, cache, config) var prevToken = tkEof diff --git a/compiler/liftdestructors.nim b/compiler/liftdestructors.nim index 11d483abb3..760ee27b5d 100644 --- a/compiler/liftdestructors.nim +++ b/compiler/liftdestructors.nim @@ -367,6 +367,8 @@ proc considerAsgnOrSink(c: var TLiftCtx; t: PType; body, x, y: PNode; op = produceSym(c.g, c.c, t, c.kind, c.info, c.idgen) body.add newHookCall(c, op, x, y) result = true + else: + result = false elif tfHasAsgn in t.flags: var op: PSym if sameType(t, c.asgnForType): @@ -396,6 +398,8 @@ proc considerAsgnOrSink(c: var TLiftCtx; t: PType; body, x, y: PNode; assert op.ast[genericParamsPos].kind == nkEmpty body.add newHookCall(c, op, x, y) result = true + else: + result = false proc addDestructorCall(c: var TLiftCtx; orig: PType; body, x: PNode) = let t = orig.skipTypes(abstractInst - {tyDistinct}) @@ -435,6 +439,8 @@ proc considerUserDefinedOp(c: var TLiftCtx; t: PType; body, x, y: PNode): bool = onUse(c.info, op) body.add destructorCall(c, op, x) result = true + else: + result = false #result = addDestructorCall(c, t, body, x) of attachedAsgn, attachedSink, attachedTrace: var op = getAttachedOp(c.g, t, c.kind) @@ -455,6 +461,8 @@ proc considerUserDefinedOp(c: var TLiftCtx; t: PType; body, x, y: PNode): bool = onUse(c.info, op) body.add newDeepCopyCall(c, op, x, y) result = true + else: + result = false of attachedWasMoved: var op = getAttachedOp(c.g, t, attachedWasMoved) @@ -469,6 +477,8 @@ proc considerUserDefinedOp(c: var TLiftCtx; t: PType; body, x, y: PNode): bool = onUse(c.info, op) body.add genWasMovedCall(c, op, x) result = true + else: + result = false of attachedDup: var op = getAttachedOp(c.g, t, attachedDup) @@ -483,6 +493,8 @@ proc considerUserDefinedOp(c: var TLiftCtx; t: PType; body, x, y: PNode): bool = onUse(c.info, op) body.add newDupCall(c, op, x, y) result = true + else: + result = false proc declareCounter(c: var TLiftCtx; body: PNode; first: BiggestInt): PNode = var temp = newSym(skTemp, getIdent(c.g.cache, lowerings.genPrefix), c.idgen, c.fn, c.info) @@ -1249,7 +1261,7 @@ proc createTypeBoundOps(g: ModuleGraph; c: PContext; orig: PType; info: TLineInf # bug #15122: We need to produce all prototypes before entering the # mind boggling recursion. Hacks like these imply we should rewrite # this module. - var generics: array[attachedWasMoved..attachedTrace, bool] + var generics: array[attachedWasMoved..attachedTrace, bool] = default(array[attachedWasMoved..attachedTrace, bool]) for k in attachedWasMoved..lastAttached: generics[k] = getAttachedOp(g, canon, k) != nil if not generics[k]: diff --git a/compiler/liftlocals.nim b/compiler/liftlocals.nim index 7ca46ab1b8..58c6189d40 100644 --- a/compiler/liftlocals.nim +++ b/compiler/liftlocals.nim @@ -49,6 +49,7 @@ proc liftLocals(n: PNode; i: int; c: var Ctx) = liftLocals(it, i, c) proc lookupParam(params, dest: PNode): PSym = + result = nil if dest.kind != nkIdent: return nil for i in 1..= 0 and x[i] == ' ': dec(i) if i >= 0 and x[i] in s: result = true + else: + result = false const LineContinuationOprs = {'+', '-', '*', '/', '\\', '<', '>', '!', '?', '^', @@ -93,6 +95,7 @@ proc continueLine(line: string, inTripleString: bool): bool {.inline.} = line.endsWith(LineContinuationOprs+AdditionalLineContinuationOprs)) proc countTriples(s: string): int = + result = 0 var i = 0 while i+2 < s.len: if s[i] == '"' and s[i+1] == '"' and s[i+2] == '"': diff --git a/compiler/lookups.nim b/compiler/lookups.nim index 17eedca924..8b9dd71fdc 100644 --- a/compiler/lookups.nim +++ b/compiler/lookups.nim @@ -298,7 +298,7 @@ proc ensureNoMissingOrUnusedSymbols(c: PContext; scope: PScope) = var it: TTabIter var s = initTabIter(it, scope.symbols) var missingImpls = 0 - var unusedSyms: seq[tuple[sym: PSym, key: string]] + var unusedSyms: seq[tuple[sym: PSym, key: string]] = @[] while s != nil: if sfForward in s.flags and s.kind notin {skType, skModule}: # too many 'implementation of X' errors are annoying @@ -458,7 +458,7 @@ proc fixSpelling(c: PContext, n: PNode, ident: PIdent, result: var string) = for (sym, depth, isLocal) in allSyms(c): let depth = -depth - 1 let dist = editDistance(name0, sym.name.s.nimIdentNormalize) - var msg: string + var msg: string = "" msg.add "\n ($1, $2): '$3'" % [$dist, $depth, sym.name.s] list.push SpellCandidate(dist: dist, depth: depth, msg: msg, sym: sym) @@ -488,6 +488,7 @@ proc errorUseQualifier(c: PContext; info: TLineInfo; s: PSym; amb: var bool): PS var err = "ambiguous identifier: '" & s.name.s & "'" var i = 0 var ignoredModules = 0 + result = nil for candidate in importedItems(c, s.name): if i == 0: err.add " -- use one of the following:\n" else: err.add "\n" @@ -586,6 +587,8 @@ proc qualifiedLookUp*(c: PContext, n: PNode, flags: set[TLookupFlag]): PSym = amb = candidates.len > 1 if amb and checkAmbiguity in flags: errorUseQualifier(c, n.info, candidates) + else: + result = nil if result == nil: let candidates = allPureEnumFields(c, ident) if candidates.len > 0: @@ -641,6 +644,7 @@ proc initOverloadIter*(o: var TOverloadIter, c: PContext, n: PNode): PSym = o.marked = initIntSet() case n.kind of nkIdent, nkAccQuoted: + result = nil var ident = considerQuotedIdent(c, n) var scope = c.currentScope o.mode = oimNoQualifier @@ -664,6 +668,7 @@ proc initOverloadIter*(o: var TOverloadIter, c: PContext, n: PNode): PSym = result = n.sym o.mode = oimDone of nkDotExpr: + result = nil o.mode = oimOtherModule o.m = qualifiedLookUp(c, n[0], {checkUndeclared, checkModule}) if o.m != nil and o.m.kind == skModule: @@ -693,7 +698,7 @@ proc initOverloadIter*(o: var TOverloadIter, c: PContext, n: PNode): PSym = o.symChoiceIndex = 1 o.marked = initIntSet() incl(o.marked, result.id) - else: discard + else: result = nil when false: if result != nil and result.kind == skStub: loadStub(result) @@ -708,6 +713,7 @@ proc lastOverloadScope*(o: TOverloadIter): int = else: result = -1 proc nextOverloadIterImports(o: var TOverloadIter, c: PContext, n: PNode): PSym = + result = nil assert o.currentScope == nil var idx = o.importIdx+1 o.importIdx = c.imports.len # assume the other imported modules lack this symbol too @@ -720,6 +726,7 @@ proc nextOverloadIterImports(o: var TOverloadIter, c: PContext, n: PNode): PSym inc idx proc symChoiceExtension(o: var TOverloadIter; c: PContext; n: PNode): PSym = + result = nil assert o.currentScope == nil while o.importIdx < c.imports.len: result = initIdentIter(o.mit, o.marked, c.imports[o.importIdx], o.it.name, c.graph) @@ -782,6 +789,8 @@ proc nextOverloadIter*(o: var TOverloadIter, c: PContext, n: PNode): PSym = break if result != nil: incl o.marked, result.id + else: + result = nil of oimSymChoiceLocalLookup: if o.currentScope != nil: result = nextIdentExcluding(o.it, o.currentScope.symbols, o.marked) @@ -805,13 +814,16 @@ proc nextOverloadIter*(o: var TOverloadIter, c: PContext, n: PNode): PSym = if result == nil: inc o.importIdx result = symChoiceExtension(o, c, n) + else: + result = nil when false: if result != nil and result.kind == skStub: loadStub(result) proc pickSym*(c: PContext, n: PNode; kinds: set[TSymKind]; flags: TSymFlags = {}): PSym = - var o: TOverloadIter + result = nil + var o: TOverloadIter = default(TOverloadIter) var a = initOverloadIter(o, c, n) while a != nil: if a.kind in kinds and flags <= a.flags: diff --git a/compiler/magicsys.nim b/compiler/magicsys.nim index becde13e6d..1b692f5d62 100644 --- a/compiler/magicsys.nim +++ b/compiler/magicsys.nim @@ -30,6 +30,7 @@ proc getSysSym*(g: ModuleGraph; info: TLineInfo; name: string): PSym = result.typ = newType(tyError, nextTypeId(g.idgen), g.systemModule) proc getSysMagic*(g: ModuleGraph; info: TLineInfo; name: string, m: TMagic): PSym = + result = nil let id = getIdent(g.cache, name) for r in systemModuleSyms(g, id): if r.magic == m: @@ -145,6 +146,7 @@ proc getMagicEqSymForType*(g: ModuleGraph; t: PType; info: TLineInfo): PSym = of tyProc: result = getSysMagic(g, info, "==", mEqProc) else: + result = nil globalError(g.config, info, "can't find magic equals operator for type kind " & $t.kind) diff --git a/compiler/main.nim b/compiler/main.nim index 364fba92e5..836f912bbc 100644 --- a/compiler/main.nim +++ b/compiler/main.nim @@ -56,7 +56,7 @@ proc writeCMakeDepsFile(conf: ConfigRef) = for it in conf.toCompile: cfiles.add(it.cname.string) let fileset = cfiles.toCountTable() # read old cfiles list - var fl: File + var fl: File = default(File) var prevset = initCountTable[string]() if open(fl, fname.string, fmRead): for line in fl.lines: prevset.inc(line) @@ -196,7 +196,7 @@ proc commandScan(cache: IdentCache, config: ConfigRef) = if stream != nil: var L: Lexer - tok: Token + tok: Token = default(Token) initToken(tok) openLexer(L, f, stream, cache, config) while true: diff --git a/compiler/modulegraphs.nim b/compiler/modulegraphs.nim index 08cdbfd0db..f9d0578b5c 100644 --- a/compiler/modulegraphs.nim +++ b/compiler/modulegraphs.nim @@ -368,6 +368,7 @@ proc copyTypeProps*(g: ModuleGraph; module: int; dest, src: PType) = setAttachedOp(g, module, dest, k, op) proc loadCompilerProc*(g: ModuleGraph; name: string): PSym = + result = nil if g.config.symbolFiles == disabledSf: return nil # slow, linear search, but the results are cached: @@ -500,6 +501,7 @@ proc resetAllModules*(g: ModuleGraph) = initModuleGraphFields(g) proc getModule*(g: ModuleGraph; fileIdx: FileIndex): PSym = + result = nil if fileIdx.int32 >= 0: if isCachedModule(g, fileIdx.int32): result = g.packed[fileIdx.int32].module @@ -605,6 +607,7 @@ proc markClientsDirty*(g: ModuleGraph; fileIdx: FileIndex) = proc needsCompilation*(g: ModuleGraph): bool = # every module that *depends* on this file is also dirty: + result = false for i in 0i32..= 0: result.add "\n" & indent & spaces(info.col) & '^' + else: + result = "" proc formatMsg*(conf: ConfigRef; info: TLineInfo, msg: TMsgKind, arg: string): string = let title = case msg diff --git a/compiler/nilcheck.nim b/compiler/nilcheck.nim index 5cc66f3ea4..96e0967702 100644 --- a/compiler/nilcheck.nim +++ b/compiler/nilcheck.nim @@ -309,6 +309,7 @@ proc symbol(n: PNode): Symbol = # echo "symbol ", n, " ", n.kind, " ", result.int func `$`(map: NilMap): string = + result = "" var now = map var stack: seq[NilMap] = @[] while not now.isNil: @@ -416,7 +417,7 @@ proc moveOut(ctx: NilCheckerContext, map: NilMap, target: PNode) = if targetSetIndex != noSetIndex: var targetSet = map.sets[targetSetIndex] if targetSet.len > 1: - var other: ExprIndex + var other: ExprIndex = default(ExprIndex) for element in targetSet: if element.ExprIndex != targetIndex: @@ -561,7 +562,7 @@ proc derefWarning(n, ctx, map; kind: Nilability) = if n.info in ctx.warningLocations: return ctx.warningLocations.incl(n.info) - var a: seq[History] + var a: seq[History] = @[] if n.kind == nkSym: a = history(map, ctx.index(n)) var res = "" @@ -765,7 +766,7 @@ proc checkIf(n, ctx, map): Check = # the state of the conditions: negating conditions before the current one var layerHistory = newNilMap(mapIf) # the state after branch effects - var afterLayer: NilMap + var afterLayer: NilMap = nil # the result nilability for expressions var nilability = Safe @@ -862,9 +863,10 @@ proc checkInfix(n, ctx, map): Check = ## a or b : map is an union of a and b's ## a == b : use checkCondition ## else: no change, just check args + result = default(Check) if n[0].kind == nkSym: - var mapL: NilMap - var mapR: NilMap + var mapL: NilMap = nil + var mapR: NilMap = nil if n[0].sym.magic notin {mAnd, mEqRef}: mapL = checkCondition(n[1], ctx, map, false, false) mapR = checkCondition(n[2], ctx, map, false, false) @@ -947,7 +949,7 @@ proc checkCase(n, ctx, map): Check = let base = n[0] result.map = map.copyMap() result.nilability = Safe - var a: PNode + var a: PNode = nil for child in n: case child.kind: of nkOfBranch: @@ -1222,7 +1224,7 @@ proc check(n: PNode, ctx: NilCheckerContext, map: NilMap): Check = # TODO deeper nested elements? # A(field: B()) # # field: Safe -> - var elements: seq[(PNode, Nilability)] + var elements: seq[(PNode, Nilability)] = @[] for i, child in n: result = check(child, ctx, result.map) if i > 0: @@ -1333,7 +1335,7 @@ proc preVisit(ctx: NilCheckerContext, s: PSym, body: PNode, conf: ConfigRef) = ctx.symbolIndices = {resultId: resultExprIndex}.toTable() var cache = newIdentCache() ctx.expressions = SeqOfDistinct[ExprIndex, PNode](@[newIdentNode(cache.getIdent("result"), s.ast.info)]) - var emptySet: IntSet # set[ExprIndex] + var emptySet: IntSet = initIntSet() # set[ExprIndex] ctx.dependants = SeqOfDistinct[ExprIndex, IntSet](@[emptySet]) for i, arg in s.typ.n.sons: if i > 0: diff --git a/compiler/nim.cfg b/compiler/nim.cfg index c32dba4d13..4c55a04cbc 100644 --- a/compiler/nim.cfg +++ b/compiler/nim.cfg @@ -43,3 +43,10 @@ define:useStdoutAsStdmsg @if nimHasWarnBareExcept: warningAserror[BareExcept]:on @end + + +@if nimUseStrictDefs: + experimental:strictDefs + warningAsError[Uninit]:on + warningAsError[ProveInit]:on +@end diff --git a/compiler/nim.nim b/compiler/nim.nim index b28e8b20c6..d05f01c427 100644 --- a/compiler/nim.nim +++ b/compiler/nim.nim @@ -91,6 +91,9 @@ proc getNimRunExe(conf: ConfigRef): string = if conf.isDefined("mingw"): if conf.isDefined("i386"): result = "wine" elif conf.isDefined("amd64"): result = "wine64" + else: result = "" + else: + result = "" proc handleCmdLine(cache: IdentCache; conf: ConfigRef) = let self = NimProg( diff --git a/compiler/nimblecmd.nim b/compiler/nimblecmd.nim index 440d35fe52..97a66f1cd9 100644 --- a/compiler/nimblecmd.nim +++ b/compiler/nimblecmd.nim @@ -37,11 +37,16 @@ proc isSpecial(ver: Version): bool = proc isValidVersion(v: string): bool = if v.len > 0: - if v[0] in {'#'} + Digits: return true + if v[0] in {'#'} + Digits: + result = true + else: + result = false + else: + result = false proc `<`*(ver: Version, ver2: Version): bool = ## This is synced from Nimble's version module. - + result = false # Handling for special versions such as "#head" or "#branch". if ver.isSpecial or ver2.isSpecial: if ver2.isSpecial and ($ver2).normalize == "#head": @@ -145,7 +150,7 @@ proc addNimblePath(conf: ConfigRef; p: string, info: TLineInfo) = conf.lazyPaths.insert(AbsoluteDir path, 0) proc addPathRec(conf: ConfigRef; dir: string, info: TLineInfo) = - var packages: PackageInfo + var packages: PackageInfo = initTable[string, tuple[version, checksum: string]]() var pos = dir.len-1 if dir[pos] in {DirSep, AltSep}: inc(pos) for k,p in os.walkDir(dir): diff --git a/compiler/nimconf.nim b/compiler/nimconf.nim index fceedb2c48..f7bae4b368 100644 --- a/compiler/nimconf.nim +++ b/compiler/nimconf.nim @@ -214,7 +214,7 @@ proc parseAssignment(L: var Lexer, tok: var Token; proc readConfigFile*(filename: AbsoluteFile; cache: IdentCache; config: ConfigRef): bool = var - L: Lexer + L: Lexer = default(Lexer) tok: Token stream: PLLStream stream = llStreamOpen(filename, fmRead) @@ -228,6 +228,8 @@ proc readConfigFile*(filename: AbsoluteFile; cache: IdentCache; if condStack.len > 0: lexMessage(L, errGenerated, "expected @end") closeLexer(L) return true + else: + result = false proc getUserConfigPath*(filename: RelativeFile): AbsoluteFile = result = getConfigDir().AbsoluteDir / RelativeDir"nim" / filename @@ -250,7 +252,7 @@ proc loadConfigs*(cfg: RelativeFile; cache: IdentCache; conf: ConfigRef; idgen: template runNimScriptIfExists(path: AbsoluteFile, isMain = false) = let p = path # eval once - var s: PLLStream + var s: PLLStream = nil if isMain and optWasNimscript in conf.globalOptions: if conf.projectIsStdin: s = stdin.llStreamOpen elif conf.projectIsCmd: s = llStreamOpen(conf.cmdInput) diff --git a/compiler/nimsets.nim b/compiler/nimsets.nim index 49c80065ae..59a542a858 100644 --- a/compiler/nimsets.nim +++ b/compiler/nimsets.nim @@ -62,7 +62,9 @@ proc someInSet*(s: PNode, a, b: PNode): bool = result = false proc toBitSet*(conf: ConfigRef; s: PNode): TBitSet = - var first, j: Int128 + result = @[] + var first: Int128 = Zero + var j: Int128 = Zero first = firstOrd(conf, s.typ[0]) bitSetInit(result, int(getSize(conf, s.typ))) for i in 0.. 0: let b = a.split(".") assert b.len == 3, a @@ -657,7 +658,7 @@ proc isDefined*(conf: ConfigRef; symbol: string): bool = of "nimrawsetjmp": result = conf.target.targetOS in {osSolaris, osNetbsd, osFreebsd, osOpenbsd, osDragonfly, osMacosx} - else: discard + else: result = false template quitOrRaise*(conf: ConfigRef, msg = "") = # xxx in future work, consider whether to also intercept `msgQuit` calls @@ -883,6 +884,7 @@ const stdPrefix = "std/" proc getRelativePathFromConfigPath*(conf: ConfigRef; f: AbsoluteFile, isTitle = false): RelativeFile = + result = RelativeFile("") let f = $f if isTitle: for dir in stdlibDirs: @@ -918,6 +920,7 @@ proc findModule*(conf: ConfigRef; modulename, currentModule: string): AbsoluteFi result = findFile(conf, m.substr(pkgPrefix.len), suppressStdlib = true) else: if m.startsWith(stdPrefix): + result = AbsoluteFile("") let stripped = m.substr(stdPrefix.len) for candidate in stdlibDirs: let path = (conf.libpath.string / candidate / stripped) diff --git a/compiler/packagehandling.nim b/compiler/packagehandling.nim index 8cf209779e..30f407792a 100644 --- a/compiler/packagehandling.nim +++ b/compiler/packagehandling.nim @@ -17,6 +17,7 @@ iterator myParentDirs(p: string): string = proc getNimbleFile*(conf: ConfigRef; path: string): string = ## returns absolute path to nimble file, e.g.: /pathto/cligen.nimble + result = "" var parents = 0 block packageSearch: for d in myParentDirs(path): diff --git a/compiler/parampatterns.nim b/compiler/parampatterns.nim index 534c3b5d18..98f5099d68 100644 --- a/compiler/parampatterns.nim +++ b/compiler/parampatterns.nim @@ -184,6 +184,7 @@ type arStrange # it is a strange beast like 'typedesc[var T]' proc exprRoot*(n: PNode; allowCalls = true): PSym = + result = nil var it = n while true: case it.kind diff --git a/compiler/parser.nim b/compiler/parser.nim index 7d12c2a785..c386df57bf 100644 --- a/compiler/parser.nim +++ b/compiler/parser.nim @@ -1177,6 +1177,7 @@ proc optPragmas(p: var Parser): PNode = proc parseDoBlock(p: var Parser; info: TLineInfo): PNode = #| doBlock = 'do' paramListArrow pragma? colcom stmt + result = nil var params = parseParamList(p, retColon=false) let pragmas = optPragmas(p) colcom(p, result) @@ -1430,6 +1431,7 @@ proc parseTypeDesc(p: var Parser, fullExpr = false): PNode = result = newNodeP(nkObjectTy, p) getTok(p) of tkConcept: + result = nil parMessage(p, "the 'concept' keyword is only valid in 'type' sections") of tkVar: result = parseTypeDescKAux(p, nkVarTy, pmTypeDesc) of tkOut: result = parseTypeDescKAux(p, nkOutTy, pmTypeDesc) diff --git a/compiler/patterns.nim b/compiler/patterns.nim index ff9a9efa34..7b0d7e4fb4 100644 --- a/compiler/patterns.nim +++ b/compiler/patterns.nim @@ -29,6 +29,8 @@ type proc getLazy(c: PPatternContext, sym: PSym): PNode = if c.mappingIsFull: result = c.mapping[sym.position] + else: + result = nil proc putLazy(c: PPatternContext, sym: PSym, n: PNode) = if not c.mappingIsFull: @@ -65,14 +67,21 @@ proc sameTrees*(a, b: PNode): bool = for i in 0..= 2: for i in 1.. 1 var key = if keyDeep: it[0] else: it diff --git a/compiler/renderer.nim b/compiler/renderer.nim index b9c3268c4c..2af8d83269 100644 --- a/compiler/renderer.nim +++ b/compiler/renderer.nim @@ -76,6 +76,8 @@ proc isKeyword*(i: PIdent): bool = if (i.id >= ord(tokKeywordLow) - ord(tkSymbol)) and (i.id <= ord(tokKeywordHigh) - ord(tkSymbol)): result = true + else: + result = false proc isExported(n: PNode): bool = ## Checks if an ident is exported. @@ -274,6 +276,7 @@ proc putComment(g: var TSrcGen, s: string) = optNL(g) proc maxLineLength(s: string): int = + result = 0 if s.len == 0: return 0 var i = 0 let hi = s.len - 1 @@ -371,6 +374,7 @@ proc litAux(g: TSrcGen; n: PNode, x: BiggestInt, size: int): string = tyLent, tyDistinct, tyOrdinal, tyAlias, tySink}: result = lastSon(result) + result = "" let typ = n.typ.skip if typ != nil and typ.kind in {tyBool, tyEnum}: if sfPure in typ.sym.flags: @@ -488,6 +492,7 @@ proc referencesUsing(n: PNode): bool = proc lsub(g: TSrcGen; n: PNode): int = # computes the length of a tree + result = 0 if isNil(n): return 0 if shouldRenderComment(g, n): return MaxLineLen + 1 case n.kind @@ -631,7 +636,7 @@ proc initContext(c: var TContext) = proc gsub(g: var TSrcGen, n: PNode, c: TContext, fromStmtList = false) proc gsub(g: var TSrcGen, n: PNode, fromStmtList = false) = - var c: TContext + var c: TContext = default(TContext) initContext(c) gsub(g, n, c, fromStmtList = fromStmtList) @@ -762,7 +767,7 @@ proc gcond(g: var TSrcGen, n: PNode) = put(g, tkParRi, ")") proc gif(g: var TSrcGen, n: PNode) = - var c: TContext + var c: TContext = default(TContext) gcond(g, n[0][0]) initContext(c) putWithSpace(g, tkColon, ":") @@ -775,7 +780,7 @@ proc gif(g: var TSrcGen, n: PNode) = gsub(g, n[i], c) proc gwhile(g: var TSrcGen, n: PNode) = - var c: TContext + var c: TContext = default(TContext) putWithSpace(g, tkWhile, "while") gcond(g, n[0]) putWithSpace(g, tkColon, ":") @@ -786,7 +791,7 @@ proc gwhile(g: var TSrcGen, n: PNode) = gstmts(g, n[1], c) proc gpattern(g: var TSrcGen, n: PNode) = - var c: TContext + var c: TContext = default(TContext) put(g, tkCurlyLe, "{") initContext(c) if longMode(g, n) or (lsub(g, n[0]) + g.lineLen > MaxLineLen): @@ -796,7 +801,7 @@ proc gpattern(g: var TSrcGen, n: PNode) = put(g, tkCurlyRi, "}") proc gpragmaBlock(g: var TSrcGen, n: PNode) = - var c: TContext + var c: TContext = default(TContext) gsub(g, n[0]) putWithSpace(g, tkColon, ":") initContext(c) @@ -806,7 +811,7 @@ proc gpragmaBlock(g: var TSrcGen, n: PNode) = gstmts(g, n[1], c) proc gtry(g: var TSrcGen, n: PNode) = - var c: TContext + var c: TContext = default(TContext) put(g, tkTry, "try") putWithSpace(g, tkColon, ":") initContext(c) @@ -817,7 +822,7 @@ proc gtry(g: var TSrcGen, n: PNode) = gsons(g, n, c, 1) proc gfor(g: var TSrcGen, n: PNode) = - var c: TContext + var c: TContext = default(TContext) putWithSpace(g, tkFor, "for") initContext(c) if longMode(g, n) or @@ -832,7 +837,7 @@ proc gfor(g: var TSrcGen, n: PNode) = gstmts(g, n[^1], c) proc gcase(g: var TSrcGen, n: PNode) = - var c: TContext + var c: TContext = default(TContext) initContext(c) if n.len == 0: return var last = if n[^1].kind == nkElse: -2 else: -1 @@ -853,7 +858,7 @@ proc genSymSuffix(result: var string, s: PSym) {.inline.} = result.addInt s.id proc gproc(g: var TSrcGen, n: PNode) = - var c: TContext + var c: TContext = default(TContext) if n[namePos].kind == nkSym: let s = n[namePos].sym var ret = renderDefinitionName(s) @@ -889,7 +894,7 @@ proc gproc(g: var TSrcGen, n: PNode) = dedent(g) proc gTypeClassTy(g: var TSrcGen, n: PNode) = - var c: TContext + var c: TContext = default(TContext) initContext(c) putWithSpace(g, tkConcept, "concept") gsons(g, n[0], c) # arglist @@ -909,7 +914,7 @@ proc gblock(g: var TSrcGen, n: PNode) = if n.len == 0: return - var c: TContext + var c: TContext = default(TContext) initContext(c) if n[0].kind != nkEmpty: @@ -930,7 +935,7 @@ proc gblock(g: var TSrcGen, n: PNode) = gstmts(g, n[1], c) proc gstaticStmt(g: var TSrcGen, n: PNode) = - var c: TContext + var c: TContext = default(TContext) putWithSpace(g, tkStatic, "static") putWithSpace(g, tkColon, ":") initContext(c) @@ -1005,6 +1010,7 @@ proc bracketKind*(g: TSrcGen, n: PNode): BracketKind = case n.kind of nkClosedSymChoice, nkOpenSymChoice: if n.len > 0: result = bracketKind(g, n[0]) + else: result = bkNone of nkSym: result = case n.sym.name.s of "[]": bkBracket @@ -1013,6 +1019,8 @@ proc bracketKind*(g: TSrcGen, n: PNode): BracketKind = of "{}=": bkCurlyAsgn else: bkNone else: result = bkNone + else: + result = bkNone proc skipHiddenNodes(n: PNode): PNode = result = n @@ -1085,11 +1093,13 @@ proc isCustomLit(n: PNode): bool = if n.len == 2 and n[0].kind == nkRStrLit: let ident = n[1].getPIdent result = ident != nil and ident.s.startsWith('\'') + else: + result = false proc gsub(g: var TSrcGen, n: PNode, c: TContext, fromStmtList = false) = if isNil(n): return var - a: TContext + a: TContext = default(TContext) if shouldRenderComment(g, n): pushCom(g, n) case n.kind # atoms: of nkTripleStrLit: put(g, tkTripleStrLit, atom(g, n)) @@ -1437,6 +1447,8 @@ proc gsub(g: var TSrcGen, n: PNode, c: TContext, fromStmtList = false) = if n.kind in {nkIdent, nkSym}: let tmp = n.getPIdent.s result = tmp.len > 0 and tmp[0] in {'a'..'z', 'A'..'Z'} + else: + result = false var useSpace = false if i == 1 and n[0].kind == nkIdent and n[0].ident.s in ["=", "'"]: if not n[1].isAlpha: # handle `=destroy`, `'big' @@ -1787,12 +1799,12 @@ proc gsub(g: var TSrcGen, n: PNode, c: TContext, fromStmtList = false) = gsub(g, n, 0) put(g, tkParRi, ")") of nkGotoState: - var c: TContext + var c: TContext = default(TContext) initContext c putWithSpace g, tkSymbol, "goto" gsons(g, n, c) of nkState: - var c: TContext + var c: TContext = default(TContext) initContext c putWithSpace g, tkSymbol, "state" gsub(g, n[0], c) @@ -1817,7 +1829,7 @@ proc gsub(g: var TSrcGen, n: PNode, c: TContext, fromStmtList = false) = proc renderTree*(n: PNode, renderFlags: TRenderFlags = {}): string = if n == nil: return "" - var g: TSrcGen + var g: TSrcGen = default(TSrcGen) initSrcGen(g, renderFlags, newPartialConfigRef()) # do not indent the initial statement list so that # writeFile("file.nim", repr n) @@ -1835,7 +1847,7 @@ proc renderModule*(n: PNode, outfile: string, fid = FileIndex(-1); conf: ConfigRef = nil) = var - f: File + f: File = default(File) g: TSrcGen initSrcGen(g, renderFlags, conf) g.fid = fid diff --git a/compiler/renderverbatim.nim b/compiler/renderverbatim.nim index 792079b3f4..00d546198a 100644 --- a/compiler/renderverbatim.nim +++ b/compiler/renderverbatim.nim @@ -40,6 +40,7 @@ type LineData = object proc tripleStrLitStartsAtNextLine(conf: ConfigRef, n: PNode): bool = # enabling TLineInfo.offsetA,offsetB would probably make this easier + result = false const tripleQuote = "\"\"\"" let src = sourceLine(conf, n.info) let col = n.info.col diff --git a/compiler/reorder.nim b/compiler/reorder.nim index 4ad3f12194..f43ddc2031 100644 --- a/compiler/reorder.nim +++ b/compiler/reorder.nim @@ -115,6 +115,7 @@ proc computeDeps(cache: IdentCache; n: PNode, declares, uses: var IntSet; topLev for i in 0.. 0: # we avoid running more diagnostic when inside a `compiles(expr)`, to # errors while running diagnostic (see test D20180828T234921), and @@ -405,8 +406,9 @@ proc resolveOverloads(c: PContext, n, orig: PNode, filter: TSymKinds, flags: TExprFlags, errors: var CandidateErrors, errorsEnabled: bool): TCandidate = + result = default(TCandidate) var initialBinding: PNode - var alt: TCandidate + var alt: TCandidate = default(TCandidate) var f = n[0] if f.kind == nkBracketExpr: # fill in the bindings: @@ -569,8 +571,8 @@ proc inheritBindings(c: PContext, x: var TCandidate, expectedType: PType) = if expectedType == nil or x.callee[0] == nil: return # required for inference var - flatUnbound: seq[PType] - flatBound: seq[PType] + flatUnbound: seq[PType] = @[] + flatBound: seq[PType] = @[] # seq[(result type, expected type)] var typeStack = newSeq[(PType, PType)]() @@ -694,7 +696,10 @@ proc semOverloadedCall(c: PContext, n, nOrig: PNode, # this time enabling all the diagnostic output (this should fail again) result = semOverloadedCall(c, n, nOrig, filter, flags + {efExplain}) elif efNoUndeclared notin flags: + result = nil notFoundError(c, n, errors) + else: + result = nil proc explicitGenericInstError(c: PContext; n: PNode): PNode = localError(c.config, getCallLineInfo(n), errCannotInstantiateX % renderTree(n)) @@ -771,6 +776,7 @@ proc searchForBorrowProc(c: PContext, startScope: PScope, fn: PSym): PSym = # for borrowing the sym in the symbol table is returned, else nil. # New approach: generate fn(x, y, z) where x, y, z have the proper types # and use the overloading resolution mechanism: + result = nil var call = newNodeI(nkCall, fn.info) var hasDistinct = false call.add(newIdentNode(fn.name, fn.info)) diff --git a/compiler/semexprs.nim b/compiler/semexprs.nim index b7fc7a9bd8..dca4ce6e0d 100644 --- a/compiler/semexprs.nim +++ b/compiler/semexprs.nim @@ -655,7 +655,7 @@ proc semArrayConstr(c: PContext, n: PNode, flags: TExprFlags; expectedType: PTyp else: discard rawAddSon(result.typ, nil) # index type var - firstIndex, lastIndex: Int128 + firstIndex, lastIndex: Int128 = Zero indexType = getSysType(c.graph, n.info, tyInt) lastValidIndex = lastOrd(c.config, indexType) if n.len == 0: @@ -990,6 +990,7 @@ proc semOverloadedCallAnalyseEffects(c: PContext, n: PNode, nOrig: PNode, proc resolveIndirectCall(c: PContext; n, nOrig: PNode; t: PType): TCandidate = + result = default(TCandidate) initCandidate(c, result, t) matches(c, n, nOrig, result) @@ -998,6 +999,8 @@ proc bracketedMacro(n: PNode): PSym = result = n[0].sym if result.kind notin {skMacro, skTemplate}: result = nil + else: + result = nil proc setGenericParams(c: PContext, n: PNode) = for i in 1.. 0: # don't interpret () as type isTupleType = tupexp[0].typ.kind == tyTypeDesc # check if either everything or nothing is tyTypeDesc @@ -2837,6 +2843,7 @@ proc semTupleConstr(c: PContext, n: PNode, flags: TExprFlags; expectedType: PTyp result = tupexp proc shouldBeBracketExpr(n: PNode): bool = + result = false assert n.kind in nkCallKinds let a = n[0] if a.kind in nkCallKinds: @@ -2854,6 +2861,8 @@ proc asBracketExpr(c: PContext; n: PNode): PNode = if n.kind in {nkIdent, nkAccQuoted}: let s = qualifiedLookUp(c, n, {}) result = s != nil and isGenericRoutineStrict(s) + else: + result = false assert n.kind in nkCallKinds if n.len > 1 and isGeneric(c, n[1]): @@ -2983,7 +2992,7 @@ proc semExpr(c: PContext, n: PNode, flags: TExprFlags = {}, expectedType: PType if nfSem in n.flags: return case n.kind of nkIdent, nkAccQuoted: - var s: PSym + var s: PSym = nil if expectedType != nil and ( let expected = expectedType.skipTypes(abstractRange-{tyDistinct}); expected.kind == tyEnum): diff --git a/compiler/semfold.nim b/compiler/semfold.nim index 07c3b3ae4e..a60bfee2a9 100644 --- a/compiler/semfold.nim +++ b/compiler/semfold.nim @@ -65,24 +65,34 @@ proc foldAdd(a, b: Int128, n: PNode; idgen: IdGenerator; g: ModuleGraph): PNode let res = a + b if checkInRange(g.config, n, res): result = newIntNodeT(res, n, idgen, g) + else: + result = nil proc foldSub(a, b: Int128, n: PNode; idgen: IdGenerator; g: ModuleGraph): PNode = let res = a - b if checkInRange(g.config, n, res): result = newIntNodeT(res, n, idgen, g) + else: + result = nil proc foldUnarySub(a: Int128, n: PNode; idgen: IdGenerator, g: ModuleGraph): PNode = if a != firstOrd(g.config, n.typ): result = newIntNodeT(-a, n, idgen, g) + else: + result = nil proc foldAbs(a: Int128, n: PNode; idgen: IdGenerator; g: ModuleGraph): PNode = if a != firstOrd(g.config, n.typ): result = newIntNodeT(abs(a), n, idgen, g) + else: + result = nil proc foldMul(a, b: Int128, n: PNode; idgen: IdGenerator; g: ModuleGraph): PNode = let res = a * b if checkInRange(g.config, n, res): return newIntNodeT(res, n, idgen, g) + else: + result = nil proc ordinalValToString*(a: PNode; g: ModuleGraph): string = # because $ has the param ordinal[T], `a` is not necessarily an enum, but an @@ -94,6 +104,7 @@ proc ordinalValToString*(a: PNode; g: ModuleGraph): string = of tyChar: result = $chr(toInt64(x) and 0xff) of tyEnum: + result = "" var n = t.n for i in 0.. 2: b = getConstExpr(m, n[2], idgen, g) @@ -396,7 +407,9 @@ proc foldConv(n, a: PNode; idgen: IdGenerator; g: ModuleGraph; check = false): P of tyBool, tyEnum: # xxx shouldn't we disallow `tyEnum`? result = a result.typ = n.typ - else: doAssert false, $srcTyp.kind + else: + result = nil + doAssert false, $srcTyp.kind of tyInt..tyInt64, tyUInt..tyUInt64: case srcTyp.kind of tyFloat..tyFloat64: @@ -420,7 +433,7 @@ proc foldConv(n, a: PNode; idgen: IdGenerator; g: ModuleGraph; check = false): P result = a result.typ = n.typ of tyOpenArray, tyVarargs, tyProc, tyPointer: - discard + result = nil else: result = a result.typ = n.typ @@ -447,21 +460,25 @@ proc foldArrayAccess(m: PSym, n: PNode; idgen: IdGenerator; g: ModuleGraph): PNo result = x.sons[idx] if result.kind == nkExprColonExpr: result = result[1] else: + result = nil localError(g.config, n.info, formatErrorIndexBound(idx, x.len-1) & $n) of nkBracket: idx -= toInt64(firstOrd(g.config, x.typ)) if idx >= 0 and idx < x.len: result = x[int(idx)] - else: localError(g.config, n.info, formatErrorIndexBound(idx, x.len-1) & $n) + else: + result = nil + localError(g.config, n.info, formatErrorIndexBound(idx, x.len-1) & $n) of nkStrLit..nkTripleStrLit: result = newNodeIT(nkCharLit, x.info, n.typ) if idx >= 0 and idx < x.strVal.len: result.intVal = ord(x.strVal[int(idx)]) else: localError(g.config, n.info, formatErrorIndexBound(idx, x.strVal.len-1) & $n) - else: discard + else: result = nil proc foldFieldAccess(m: PSym, n: PNode; idgen: IdGenerator; g: ModuleGraph): PNode = # a real field access; proc calls have already been transformed + result = nil if n[1].kind != nkSym: return nil var x = getConstExpr(m, n[0], idgen, g) if x == nil or x.kind notin {nkObjConstr, nkPar, nkTupleConstr}: return @@ -496,6 +513,7 @@ proc newSymNodeTypeDesc*(s: PSym; idgen: IdGenerator; info: TLineInfo): PNode = result.typ = s.typ proc foldDefine(m, s: PSym, n: PNode; idgen: IdGenerator; g: ModuleGraph): PNode = + result = nil var name = s.name.s let prag = extractPragma(s) if prag != nil: diff --git a/compiler/semgnrc.nim b/compiler/semgnrc.nim index 70cb64b516..43b8d4bac4 100644 --- a/compiler/semgnrc.nim +++ b/compiler/semgnrc.nim @@ -59,6 +59,7 @@ template isMixedIn(sym): bool = proc semGenericStmtSymbol(c: PContext, n: PNode, s: PSym, ctx: var GenericCtx; flags: TSemGenericFlags, fromDotExpr=false): PNode = + result = nil semIdeForTemplateOrGenericCheck(c.config, n, ctx.cursorInBody) incl(s.flags, sfUsed) template maybeDotChoice(c: PContext, n: PNode, s: PSym, fromDotExpr: bool) = @@ -439,7 +440,7 @@ proc semGenericStmt(c: PContext, n: PNode, if n[0].kind != nkEmpty: n[0] = semGenericStmt(c, n[0], flags+{withinTypeDesc}, ctx) for i in 1..= 0 and c.locals[s].stride != nil: result = c.locals[s].stride.intVal + else: + result = 0 else: + result = 0 for i in 0..= 1: p[0] else: p @@ -2251,7 +2266,7 @@ proc semGenericParamList(c: PContext, n: PNode, father: PType = nil): PNode = of nkIdentDefs: var def = a[^1] let constraint = a[^2] - var typ: PType + var typ: PType = nil if constraint.kind != nkEmpty: typ = semTypeNode(c, constraint, nil) diff --git a/compiler/semtypinst.nim b/compiler/semtypinst.nim index 7c9bf9039d..19aa8be291 100644 --- a/compiler/semtypinst.nim +++ b/compiler/semtypinst.nim @@ -36,6 +36,7 @@ proc checkConstructedType*(conf: ConfigRef; info: TLineInfo, typ: PType) = localError(info, errInheritanceOnlyWithNonFinalObjects) proc searchInstTypes*(g: ModuleGraph; key: PType): PType = + result = nil let genericTyp = key[0] if not (genericTyp.kind == tyGenericBody and genericTyp.sym != nil): return @@ -100,6 +101,7 @@ proc newTypeMapLayer*(cl: var TReplTypeVars): LayeredIdTable = initIdTable(result.topLayer) proc lookup(typeMap: LayeredIdTable, key: PType): PType = + result = nil var tm = typeMap while tm != nil: result = PType(idTableGet(tm.topLayer, key)) @@ -683,6 +685,7 @@ proc replaceTypeVarsTAux(cl: var TReplTypeVars, t: PType): PType = proc initTypeVars*(p: PContext, typeMap: LayeredIdTable, info: TLineInfo; owner: PSym): TReplTypeVars = + result = default(TReplTypeVars) initIdTable(result.symMap) initIdTable(result.localCache) result.typeMap = typeMap diff --git a/compiler/sighashes.nim b/compiler/sighashes.nim index 2d91fb2a01..9940d0c68e 100644 --- a/compiler/sighashes.nim +++ b/compiler/sighashes.nim @@ -159,7 +159,7 @@ proc hashType(c: var MD5Context, t: PType; flags: set[ConsiderFlag]; conf: Confi else: c.hashSym(t.sym) - var symWithFlags: PSym + var symWithFlags: PSym = nil template hasFlag(sym): bool = let ret = {sfAnon, sfGenSym} * sym.flags != {} if ret: symWithFlags = sym @@ -260,6 +260,7 @@ when defined(debugSigHashes): # (select hash from sighashes group by hash having count(*) > 1) order by hash; proc hashType*(t: PType; conf: ConfigRef; flags: set[ConsiderFlag] = {CoType}): SigHash = + result = default(SigHash) var c: MD5Context md5Init c hashType c, t, flags+{CoOwnerSig}, conf @@ -269,6 +270,7 @@ proc hashType*(t: PType; conf: ConfigRef; flags: set[ConsiderFlag] = {CoType}): typeToString(t), $result) proc hashProc(s: PSym; conf: ConfigRef): SigHash = + result = default(SigHash) var c: MD5Context md5Init c hashType c, s.typ, {CoProc}, conf @@ -289,6 +291,7 @@ proc hashProc(s: PSym; conf: ConfigRef): SigHash = md5Final c, result.MD5Digest proc hashNonProc*(s: PSym): SigHash = + result = default(SigHash) var c: MD5Context md5Init c hashSym(c, s) @@ -305,6 +308,7 @@ proc hashNonProc*(s: PSym): SigHash = md5Final c, result.MD5Digest proc hashOwner*(s: PSym): SigHash = + result = default(SigHash) var c: MD5Context md5Init c var m = s @@ -374,7 +378,7 @@ proc symBodyDigest*(graph: ModuleGraph, sym: PSym): SigHash = ## compute unique digest of the proc/func/method symbols ## recursing into invoked symbols as well assert(sym.kind in skProcKinds, $sym.kind) - + result = default(SigHash) graph.symBodyHashes.withValue(sym.id, value): return value[] diff --git a/compiler/sigmatch.nim b/compiler/sigmatch.nim index 12cc1fcb12..9bf47df700 100644 --- a/compiler/sigmatch.nim +++ b/compiler/sigmatch.nim @@ -170,9 +170,11 @@ proc initCandidate*(ctx: PContext, c: var TCandidate, callee: PSym, proc newCandidate*(ctx: PContext, callee: PSym, binding: PNode, calleeScope = -1): TCandidate = + result = default(TCandidate) initCandidate(ctx, result, callee, binding, calleeScope) proc newCandidate*(ctx: PContext, callee: PType): TCandidate = + result = default(TCandidate) initCandidate(ctx, result, callee) proc copyCandidate(a: var TCandidate, b: TCandidate) = @@ -214,6 +216,7 @@ proc sumGeneric(t: PType): int = # count the "genericness" so that Foo[Foo[T]] has the value 3 # and Foo[T] has the value 2 so that we know Foo[Foo[T]] is more # specific than Foo[T]. + result = 0 var t = t var isvar = 0 while true: @@ -344,6 +347,7 @@ template describeArgImpl(c: PContext, n: PNode, i: int, startIdx = 1; prefer = p result.add argTypeToString(arg, prefer) proc describeArg*(c: PContext, n: PNode, i: int, startIdx = 1; prefer = preferName): string = + result = "" describeArgImpl(c, n, i, startIdx, prefer) proc describeArgs*(c: PContext, n: PNode, startIdx = 1; prefer = preferName): string = @@ -440,6 +444,8 @@ proc isConvertibleToRange(c: PContext, f, a: PType): bool = # `isIntLit` is correct and should be used above as well, see PR: # https://github.com/nim-lang/Nim/pull/11197 result = isIntLit(a) or a.kind in {tyFloat..tyFloat128} + else: + result = false proc handleFloatRange(f, a: PType): TTypeRelation = if a.kind == f.kind: @@ -506,6 +512,7 @@ proc skipToObject(t: PType; skipped: var SkippedPtr): PType = else: break if r.kind == tyObject and ptrs <= 1: result = r + else: result = nil proc isGenericSubtype(c: var TCandidate; a, f: PType, d: var int, fGenericOrigin: PType): bool = assert f.kind in {tyGenericInst, tyGenericInvocation, tyGenericBody} @@ -528,6 +535,8 @@ proc isGenericSubtype(c: var TCandidate; a, f: PType, d: var int, fGenericOrigin genericParamPut(c, last, fGenericOrigin) d = depth result = true + else: + result = false proc minRel(a, b: TTypeRelation): TTypeRelation = if a <= b: result = a @@ -609,6 +618,8 @@ proc procParamTypeRel(c: var TCandidate, f, a: PType): TTypeRelation = if reverseRel >= isGeneric: result = isInferred #inc c.genericMatches + else: + result = isNone else: # Note that this typeRel call will save f's resolved type into c.bindings # if f is metatype. @@ -656,7 +667,7 @@ proc procTypeRel(c: var TCandidate, f, a: PType): TTypeRelation = of tyNil: result = f.allowsNil - else: discard + else: result = isNone proc typeRangeRel(f, a: PType): TTypeRelation {.noinline.} = template checkRange[T](a0, a1, f0, f1: T): TTypeRelation = @@ -701,14 +712,14 @@ proc matchUserTypeClass*(m: var TCandidate; ff, a: PType): PType = typeClass[0][0] = prevCandidateType closeScope(c) - var typeParams: seq[(PSym, PType)] + var typeParams: seq[(PSym, PType)] = @[] if ff.kind == tyUserTypeClassInst: for i in 1..<(ff.len - 1): var typeParamName = ff.base[i-1].sym.name typ = ff[i] - param: PSym + param: PSym = nil alreadyBound = PType(idTableGet(m.bindings, typ)) if alreadyBound != nil: typ = alreadyBound @@ -748,8 +759,8 @@ proc matchUserTypeClass*(m: var TCandidate; ff, a: PType): PType = addDecl(c, param) var - oldWriteHook: typeof(m.c.config.writelnHook) - diagnostics: seq[string] + oldWriteHook = default typeof(m.c.config.writelnHook) + diagnostics: seq[string] = @[] errorPrefix: string flags: TExprFlags = {} collectDiagnostics = m.diagnosticsEnabled or @@ -923,6 +934,7 @@ proc inferStaticsInRange(c: var TCandidate, else: failureToInferStaticParam(c.c.config, exp) + result = isNone if lowerBound.kind == nkIntLit: if upperBound.kind == nkIntLit: if lengthOrd(c.c.config, concrete) == upperBound.intVal - lowerBound.intVal + 1: @@ -2465,7 +2477,7 @@ proc matchesAux(c: PContext, n, nOrig: PNode, m: var TCandidate, marker: var Int a = 1 # iterates over the actual given arguments f = if m.callee.kind != tyGenericBody: 1 else: 0 # iterates over formal parameters - arg: PNode # current prepared argument + arg: PNode = nil # current prepared argument formalLen = m.callee.n.len formal = if formalLen > 1: m.callee.n[1].sym else: nil # current routine parameter container: PNode = nil # constructed container @@ -2726,6 +2738,7 @@ proc instTypeBoundOp*(c: PContext; dc: PSym; t: PType; info: TLineInfo; else: if f.kind in {tyVar}: f = f.lastSon if typeRel(m, f, t) == isNone: + result = nil localError(c.config, info, "cannot instantiate: '" & dc.name.s & "'") else: result = c.semGenerateInstance(c, dc, m.bindings, info) diff --git a/compiler/sizealignoffsetimpl.nim b/compiler/sizealignoffsetimpl.nim index e07d55fbcd..99e4342bbb 100644 --- a/compiler/sizealignoffsetimpl.nim +++ b/compiler/sizealignoffsetimpl.nim @@ -503,6 +503,7 @@ template foldOffsetOf*(conf: ConfigRef; n: PNode; fallback: PNode): PNode = elif node[1].kind == nkCheckedFieldExpr: dotExpr = node[1][0] else: + dotExpr = nil localError(config, node.info, "can't compute offsetof on this ast") assert dotExpr != nil diff --git a/compiler/sourcemap.nim b/compiler/sourcemap.nim index 2fcc50bbe9..b0b6fea2ef 100644 --- a/compiler/sourcemap.nim +++ b/compiler/sourcemap.nim @@ -70,6 +70,7 @@ func encode*(values: seq[int]): string {.raises: [].} = shift = 5 continueBit = 1 shl 5 mask = continueBit - 1 + result = "" for val in values: # Sign is stored in first bit var newVal = abs(val) shl 1 @@ -101,8 +102,8 @@ iterator tokenize*(line: string): (int, string) = token = "" while col < line.len: var - token: string - name: string + token: string = "" + name: string = "" # First we find the next identifier col += line.skipWhitespace(col) col += line.skipUntil(IdentStartChars, col) @@ -110,7 +111,7 @@ iterator tokenize*(line: string): (int, string) = col += line.parseIdent(token, col) # Idents will either be originalName_randomInt or HEXhexCode_randomInt if token.startsWith("HEX"): - var hex: int + var hex: int = 0 # 3 = "HEX".len and we only want to parse the two integers after it discard token[3 ..< 5].parseHex(hex) name = $chr(hex) @@ -125,6 +126,7 @@ iterator tokenize*(line: string): (int, string) = func parse*(source: string): SourceInfo = ## Parses the JS output for embedded line info ## So it can convert those into a series of mappings + result = default(SourceInfo) var skipFirstLine = true currColumn = 0 @@ -133,9 +135,9 @@ func parse*(source: string): SourceInfo = # Add each line as a node into the output for line in source.splitLines(): var - lineNumber: int - linePath: string - column: int + lineNumber: int = 0 + linePath: string = "" + column: int = 0 if line.strip().scanf("/* line $i:$i \"$+\" */", lineNumber, column, linePath): # When we reach the first line mappinsegmentg then we can assume # we can map the rest of the JS lines to Nim lines diff --git a/compiler/spawn.nim b/compiler/spawn.nim index 7423fdfaa4..e6c089966f 100644 --- a/compiler/spawn.nim +++ b/compiler/spawn.nim @@ -114,7 +114,7 @@ proc createWrapperProc(g: ModuleGraph; f: PNode; threadParam, argsParam: PSym; idgen: IdGenerator; spawnKind: TSpawnResult, result: PSym) = var body = newNodeI(nkStmtList, f.info) - var threadLocalBarrier: PSym + var threadLocalBarrier: PSym = nil if barrier != nil: var varSection2 = newNodeI(nkVarSection, barrier.info) threadLocalBarrier = addLocalVar(g, varSection2, nil, idgen, result, @@ -122,7 +122,7 @@ proc createWrapperProc(g: ModuleGraph; f: PNode; threadParam, argsParam: PSym; body.add varSection2 body.add callCodegenProc(g, "barrierEnter", threadLocalBarrier.info, threadLocalBarrier.newSymNode) - var threadLocalProm: PSym + var threadLocalProm: PSym = nil if spawnKind == srByVar: threadLocalProm = addLocalVar(g, varSection, nil, idgen, result, fv.typ, fv) elif fv != nil: diff --git a/compiler/suggest.nim b/compiler/suggest.nim index ca19b24605..c7efad1af6 100644 --- a/compiler/suggest.nim +++ b/compiler/suggest.nim @@ -55,6 +55,8 @@ proc findDocComment(n: PNode): PNode = result = findDocComment(n[1]) elif n.kind in {nkAsgn, nkFastAsgn, nkSinkAsgn} and n.len == 2: result = findDocComment(n[1]) + else: + result = nil proc extractDocComment(g: ModuleGraph; s: PSym): string = var n = findDocComment(s.ast) @@ -106,7 +108,7 @@ proc getTokenLenFromSource(conf: ConfigRef; ident: string; info: TLineInfo): int if cmpIgnoreStyle(line[column..column + result - 1], ident) != 0: result = 0 else: - var sourceIdent: string + var sourceIdent: string = "" result = parseWhile(line, sourceIdent, OpChars + {'[', '(', '{', ']', ')', '}'}, column) if ident[^1] == '=' and ident[0] in linter.Letters: @@ -254,13 +256,17 @@ proc filterSym(s: PSym; prefix: PNode; res: var PrefixMatch): bool {.inline.} = of nkOpenSymChoice, nkClosedSymChoice, nkAccQuoted: if n.len > 0: result = prefixMatch(s, n[0]) - else: discard + else: + result = default(PrefixMatch) + else: result = default(PrefixMatch) if s.kind != skModule: if prefix != nil: res = prefixMatch(s, prefix) result = res != PrefixMatch.None else: result = true + else: + result = false proc filterSymNoOpr(s: PSym; prefix: PNode; res: var PrefixMatch): bool {.inline.} = result = filterSym(s, prefix, res) and s.name.s[0] in lexer.SymChars and @@ -294,7 +300,7 @@ proc getQuality(s: PSym): range[0..100] = result = result - 5 proc suggestField(c: PContext, s: PSym; f: PNode; info: TLineInfo; outputs: var Suggestions) = - var pm: PrefixMatch + var pm: PrefixMatch = default(PrefixMatch) if filterSym(s, f, pm) and fieldVisible(c, s): outputs.add(symToSuggest(c.graph, s, isLocal=true, ideSug, info, s.getQuality, pm, c.inTypeContext > 0, 0)) @@ -302,7 +308,7 @@ proc suggestField(c: PContext, s: PSym; f: PNode; info: TLineInfo; outputs: var template wholeSymTab(cond, section: untyped) {.dirty.} = for (item, scopeN, isLocal) in uniqueSyms(c): let it = item - var pm: PrefixMatch + var pm: PrefixMatch = default(PrefixMatch) if cond: outputs.add(symToSuggest(c.graph, it, isLocal = isLocal, section, info, getQuality(it), pm, c.inTypeContext > 0, scopeN)) @@ -365,6 +371,8 @@ proc typeFits(c: PContext, s: PSym, firstArg: PType): bool {.inline.} = if exp.kind == tyVarargs: exp = elemType(exp) if exp.kind in {tyUntyped, tyTyped, tyGenericParam, tyAnything}: return result = sigmatch.argtypeMatches(c, s.typ[1], firstArg) + else: + result = false proc suggestOperations(c: PContext, n, f: PNode, typ: PType, outputs: var Suggestions) = assert typ != nil @@ -374,7 +382,7 @@ proc suggestOperations(c: PContext, n, f: PNode, typ: PType, outputs: var Sugges proc suggestEverything(c: PContext, n, f: PNode, outputs: var Suggestions) = # do not produce too many symbols: for (it, scopeN, isLocal) in uniqueSyms(c): - var pm: PrefixMatch + var pm: PrefixMatch = default(PrefixMatch) if filterSym(it, f, pm): outputs.add(symToSuggest(c.graph, it, isLocal = isLocal, ideSug, n.info, it.getQuality, pm, c.inTypeContext > 0, scopeN)) @@ -383,7 +391,7 @@ proc suggestFieldAccess(c: PContext, n, field: PNode, outputs: var Suggestions) # special code that deals with ``myObj.``. `n` is NOT the nkDotExpr-node, but # ``myObj``. var typ = n.typ - var pm: PrefixMatch + var pm: PrefixMatch = default(PrefixMatch) when defined(nimsuggest): if n.kind == nkSym and n.sym.kind == skError and c.config.suggestVersion == 0: # consider 'foo.|' where 'foo' is some not imported module. @@ -445,7 +453,7 @@ proc suggestFieldAccess(c: PContext, n, field: PNode, outputs: var Suggestions) for node in typ.n: if node.kind == nkSym: let s = node.sym - var pm: PrefixMatch + var pm: PrefixMatch = default(PrefixMatch) if filterSym(s, field, pm): outputs.add(symToSuggest(c.graph, s, isLocal=true, ideSug, n.info, s.getQuality, pm, c.inTypeContext > 0, 0)) @@ -460,17 +468,24 @@ type proc inCheckpoint*(current, trackPos: TLineInfo): TCheckPointResult = if current.fileIndex == trackPos.fileIndex: + result = cpNone if current.line == trackPos.line and abs(current.col-trackPos.col) < 4: return cpExact if current.line >= trackPos.line: return cpFuzzy + else: + result = cpNone proc isTracked*(current, trackPos: TLineInfo, tokenLen: int): bool = if current.fileIndex==trackPos.fileIndex and current.line==trackPos.line: let col = trackPos.col if col >= current.col and col <= current.col+tokenLen-1: - return true + result = true + else: + result = false + else: + result = false when defined(nimsuggest): # Since TLineInfo defined a == operator that doesn't include the column, @@ -700,7 +715,7 @@ proc suggestSentinel*(c: PContext) = var outputs: Suggestions = @[] # suggest everything: for (it, scopeN, isLocal) in uniqueSyms(c): - var pm: PrefixMatch + var pm: PrefixMatch = default(PrefixMatch) if filterSymNoOpr(it, nil, pm): outputs.add(symToSuggest(c.graph, it, isLocal = isLocal, ideSug, newLineInfo(c.config.m.trackPos.fileIndex, 0, -1), it.getQuality, diff --git a/compiler/syntaxes.nim b/compiler/syntaxes.nim index c00fe8b677..1c8acf2a64 100644 --- a/compiler/syntaxes.nim +++ b/compiler/syntaxes.nim @@ -36,6 +36,8 @@ proc containsShebang(s: string, i: int): bool = var j = i + 2 while j < s.len and s[j] in Whitespace: inc(j) result = s[j] == '/' + else: + result = false proc parsePipe(filename: AbsoluteFile, inputStream: PLLStream; cache: IdentCache; config: ConfigRef): PNode = @@ -64,6 +66,7 @@ proc parsePipe(filename: AbsoluteFile, inputStream: PLLStream; cache: IdentCache llStreamClose(s) proc getFilter(ident: PIdent): FilterKind = + result = filtNone for i in FilterKind: if cmpIgnoreStyle(ident.s, $i) == 0: return i @@ -74,6 +77,7 @@ proc getCallee(conf: ConfigRef; n: PNode): PIdent = elif n.kind == nkIdent: result = n.ident else: + result = nil localError(conf, n.info, "invalid filter: " & renderTree(n)) proc applyFilter(p: var Parser, n: PNode, filename: AbsoluteFile, @@ -124,7 +128,7 @@ proc openParser*(p: var Parser, fileIdx: FileIndex, inputstream: PLLStream; proc setupParser*(p: var Parser; fileIdx: FileIndex; cache: IdentCache; config: ConfigRef): bool = let filename = toFullPathConsiderDirty(config, fileIdx) - var f: File + var f: File = default(File) if not open(f, filename.string): rawMessage(config, errGenerated, "cannot open file: " & filename.string) return false @@ -132,7 +136,9 @@ proc setupParser*(p: var Parser; fileIdx: FileIndex; cache: IdentCache; result = true proc parseFile*(fileIdx: FileIndex; cache: IdentCache; config: ConfigRef): PNode = - var p: Parser + var p: Parser = default(Parser) if setupParser(p, fileIdx, cache, config): result = parseAll(p) closeParser(p) + else: + result = nil diff --git a/compiler/transf.nim b/compiler/transf.nim index d0428b725d..92d740276b 100644 --- a/compiler/transf.nim +++ b/compiler/transf.nim @@ -242,9 +242,10 @@ proc transformConstSection(c: PTransf, v: PNode): PNode = proc hasContinue(n: PNode): bool = case n.kind - of nkEmpty..nkNilLit, nkForStmt, nkParForStmt, nkWhileStmt: discard + of nkEmpty..nkNilLit, nkForStmt, nkParForStmt, nkWhileStmt: result = false of nkContinueStmt: result = true else: + result = false for i in 0.. 0: n[0] else: n @@ -145,12 +156,14 @@ proc isNoSideEffectPragma*(n: PNode): bool = result = k == wNoSideEffect proc findPragma*(n: PNode, which: TSpecialWord): PNode = + result = nil if n.kind == nkPragma: for son in n: if whichPragma(son) == which: return son proc effectSpec*(n: PNode, effectType: TSpecialWord): PNode = + result = nil for i in 0.. 0: assert(t.n[0].kind == nkSym) result = toInt128(t.n[0].sym.position) + else: + result = Zero of tyGenericInst, tyDistinct, tyTypeDesc, tyAlias, tySink, tyStatic, tyInferred, tyUserTypeClasses, tyLent: result = firstOrd(conf, lastSon(t)) of tyOrdinal: if t.len > 0: result = firstOrd(conf, lastSon(t)) - else: internalError(conf, "invalid kind for firstOrd(" & $t.kind & ')') + else: + result = Zero + internalError(conf, "invalid kind for firstOrd(" & $t.kind & ')') of tyUncheckedArray, tyCstring: result = Zero else: - internalError(conf, "invalid kind for firstOrd(" & $t.kind & ')') result = Zero + internalError(conf, "invalid kind for firstOrd(" & $t.kind & ')') proc firstFloat*(t: PType): BiggestFloat = case t.kind @@ -834,14 +840,14 @@ proc targetSizeSignedToKind*(conf: ConfigRef): TTypeKind = of 8: result = tyInt64 of 4: result = tyInt32 of 2: result = tyInt16 - else: discard + else: result = tyNone proc targetSizeUnsignedToKind*(conf: ConfigRef): TTypeKind = case conf.target.intSize of 8: result = tyUInt64 of 4: result = tyUInt32 of 2: result = tyUInt16 - else: discard + else: result = tyNone proc normalizeKind*(conf: ConfigRef, k: TTypeKind): TTypeKind = case k @@ -869,7 +875,7 @@ proc lastOrd*(conf: ConfigRef; t: PType): Int128 = of 4: result = toInt128(0x7FFFFFFF) of 2: result = toInt128(0x00007FFF) of 1: result = toInt128(0x0000007F) - else: discard + else: result = Zero else: result = toInt128(0x7FFFFFFFFFFFFFFF'u64) of tyInt8: result = toInt128(0x0000007F) of tyInt16: result = toInt128(0x00007FFF) @@ -889,18 +895,22 @@ proc lastOrd*(conf: ConfigRef; t: PType): Int128 = if t.n.len > 0: assert(t.n[^1].kind == nkSym) result = toInt128(t.n[^1].sym.position) + else: + result = Zero of tyGenericInst, tyDistinct, tyTypeDesc, tyAlias, tySink, tyStatic, tyInferred, tyUserTypeClasses, tyLent: result = lastOrd(conf, lastSon(t)) of tyProxy: result = Zero of tyOrdinal: if t.len > 0: result = lastOrd(conf, lastSon(t)) - else: internalError(conf, "invalid kind for lastOrd(" & $t.kind & ')') + else: + result = Zero + internalError(conf, "invalid kind for lastOrd(" & $t.kind & ')') of tyUncheckedArray: result = Zero else: - internalError(conf, "invalid kind for lastOrd(" & $t.kind & ')') result = Zero + internalError(conf, "invalid kind for lastOrd(" & $t.kind & ')') proc lastFloat*(t: PType): BiggestFloat = case t.kind @@ -972,7 +982,7 @@ type proc initSameTypeClosure: TSameTypeClosure = # we do the initialization lazily for performance (avoids memory allocations) - discard + result = TSameTypeClosure() proc containsOrIncl(c: var TSameTypeClosure, a, b: PType): bool = result = c.s.len > 0 and c.s.contains((a.id, b.id)) @@ -1011,6 +1021,8 @@ proc equalParam(a, b: PSym): TParamsEquality = result = paramsEqual elif b.ast != nil: result = paramsIncompatible + else: + result = paramsNotEqual else: result = paramsNotEqual @@ -1078,6 +1090,8 @@ proc sameTuple(a, b: PType, c: var TSameTypeClosure): bool = return false elif a.n != b.n and (a.n == nil or b.n == nil) and IgnoreTupleFields notin c.flags: result = false + else: + result = false template ifFastObjectTypeCheckFailed(a, b: PType, body: untyped) = if tfFromGeneric notin a.flags + b.flags: @@ -1097,6 +1111,8 @@ template ifFastObjectTypeCheckFailed(a, b: PType, body: untyped) = if tfFromGeneric in a.flags * b.flags and a.sym.id == b.sym.id: # ok, we need the expensive structural check body + else: + result = false proc sameObjectTypes*(a, b: PType): bool = # specialized for efficiency (sigmatch uses it) @@ -1134,6 +1150,12 @@ proc sameObjectTree(a, b: PNode, c: var TSameTypeClosure): bool = for i in 0.. 1: # we know the result is derived from the first argument: - var roots: seq[(PSym, int)] + var roots: seq[(PSym, int)] = @[] allRoots(n[1], roots, RootEscapes) for r in roots: connect(c, dest.sym, r[0], n[1].info) @@ -618,7 +620,8 @@ proc deps(c: var Partitions; dest, src: PNode) = if borrowChecking in c.goals: borrowingAsgn(c, dest, src) - var targets, sources: seq[(PSym, int)] + var targets: seq[(PSym, int)] = @[] + var sources: seq[(PSym, int)] = @[] allRoots(dest, targets, 0) allRoots(src, sources, 0) @@ -668,7 +671,7 @@ proc potentialMutationViaArg(c: var Partitions; n: PNode; callee: PType) = if constParameters in c.goals and tfNoSideEffect in callee.flags: discard "we know there are no hidden mutations through an immutable parameter" elif c.inNoSideEffectSection == 0 and containsPointer(n.typ): - var roots: seq[(PSym, int)] + var roots: seq[(PSym, int)] = @[] allRoots(n, roots, RootEscapes) for r in roots: potentialMutation(c, r[0], r[1], n.info) @@ -716,7 +719,7 @@ proc traverse(c: var Partitions; n: PNode) = if i < L: let paramType = parameters[i].skipTypes({tyGenericInst, tyAlias}) if not paramType.isCompileTimeOnly and paramType.kind in {tyVar, tySink, tyOwned}: - var roots: seq[(PSym, int)] + var roots: seq[(PSym, int)] = @[] allRoots(it, roots, RootEscapes) if paramType.kind == tyVar: if c.inNoSideEffectSection == 0: diff --git a/compiler/vm.nim b/compiler/vm.nim index 7376ff165e..1f4e4333d0 100644 --- a/compiler/vm.nim +++ b/compiler/vm.nim @@ -381,6 +381,7 @@ proc cleanUpOnReturn(c: PCtx; f: PStackFrame): int = return pc + 1 proc opConv(c: PCtx; dest: var TFullReg, src: TFullReg, desttyp, srctyp: PType): bool = + result = false if desttyp.kind == tyString: dest.ensureKind(rkNode) dest.node = newNode(nkStrLit) @@ -548,11 +549,12 @@ proc takeCharAddress(c: PCtx, src: PNode, index: BiggestInt, pc: int): TFullReg proc rawExecute(c: PCtx, start: int, tos: PStackFrame): TFullReg = + result = TFullReg(kind: rkNone) var pc = start var tos = tos # Used to keep track of where the execution is resumed. var savedPC = -1 - var savedFrame: PStackFrame + var savedFrame: PStackFrame = nil when defined(gcArc) or defined(gcOrc) or defined(gcAtomicArc): template updateRegsAlias = discard template regs: untyped = tos.slots @@ -1381,7 +1383,7 @@ proc rawExecute(c: PCtx, start: int, tos: PStackFrame): TFullReg = let prcValue = c.globals[prc.position-1] if prcValue.kind == nkEmpty: globalError(c.config, c.debug[pc], "cannot run " & prc.name.s) - var slots2: TNodeSeq + var slots2: TNodeSeq = default(TNodeSeq) slots2.setLen(tos.slots.len) for i in 0..= 0 # 'nim check' does not like this internalAssert. if tmp >= 0: result = TRegister(tmp) + else: + result = 0 proc clearDest(c: PCtx; n: PNode; dest: var TDest) {.inline.} = # stmt is different from 'void' in meta programming contexts. @@ -830,10 +832,14 @@ proc genVarargsABC(c: PCtx; n: PNode; dest: var TDest; opc: TOpcode) = proc isInt8Lit(n: PNode): bool = if n.kind in {nkCharLit..nkUInt64Lit}: result = n.intVal >= low(int8) and n.intVal <= high(int8) + else: + result = false proc isInt16Lit(n: PNode): bool = if n.kind in {nkCharLit..nkUInt64Lit}: result = n.intVal >= low(int16) and n.intVal <= high(int16) + else: + result = false proc genAddSubInt(c: PCtx; n: PNode; dest: var TDest; opc: TOpcode) = if n[2].isInt8Lit: @@ -854,7 +860,9 @@ proc genConv(c: PCtx; n, arg: PNode; dest: var TDest; opc=opcConv) = # xxx consider whether to use t2 and targ2 here if n.typ.kind == arg.typ.kind and arg.typ.kind == tyProc: # don't do anything for lambda lifting conversions: - return true + result = true + else: + result = false if implicitConv(): gen(c, arg, dest) @@ -1419,6 +1427,7 @@ proc unneededIndirection(n: PNode): bool = n.typ.skipTypes(abstractInstOwned-{tyTypeDesc}).kind == tyRef proc canElimAddr(n: PNode; idgen: IdGenerator): PNode = + result = nil case n[0].kind of nkObjUpConv, nkObjDownConv, nkChckRange, nkChckRangeF, nkChckRange64: var m = n[0][0] @@ -1500,6 +1509,7 @@ proc cannotEval(c: PCtx; n: PNode) {.noinline.} = n.renderTree) proc isOwnedBy(a, b: PSym): bool = + result = false var a = a.owner while a != nil and a.kind != skModule: if a == b: return true @@ -1512,7 +1522,9 @@ proc getOwner(c: PCtx): PSym = proc importcCondVar*(s: PSym): bool {.inline.} = # see also importcCond if sfImportc in s.flags: - return s.kind in {skVar, skLet, skConst} + result = s.kind in {skVar, skLet, skConst} + else: + result = false proc checkCanEval(c: PCtx; n: PNode) = # we need to ensure that we don't evaluate 'x' here: @@ -1635,6 +1647,7 @@ proc isEmptyBody(n: PNode): bool = proc importcCond*(c: PCtx; s: PSym): bool {.inline.} = ## return true to importc `s`, false to execute its body instead (refs #8405) + result = false if sfImportc in s.flags: if s.kind in routineKinds: return isEmptyBody(getBody(c.graph, s)) @@ -2048,6 +2061,7 @@ proc genTupleConstr(c: PCtx, n: PNode, dest: var TDest) = proc genProc*(c: PCtx; s: PSym): int proc toKey(s: PSym): string = + result = "" var s = s while s != nil: result.add s.name.s @@ -2334,7 +2348,7 @@ proc genProc(c: PCtx; s: PSym): int = #if s.name.s == "outterMacro" or s.name.s == "innerProc": # echo "GENERATING CODE FOR ", s.name.s let last = c.code.len-1 - var eofInstr: TInstr + var eofInstr: TInstr = default(TInstr) if last >= 0 and c.code[last].opcode == opcEof: eofInstr = c.code[last] c.code.setLen(last) diff --git a/compiler/vmhooks.nim b/compiler/vmhooks.nim index 1741574b86..7d9e66104c 100644 --- a/compiler/vmhooks.nim +++ b/compiler/vmhooks.nim @@ -69,7 +69,9 @@ proc getVar*(a: VmArgs; i: Natural): PNode = case p.kind of rkRegisterAddr: result = p.regAddr.node of rkNodeAddr: result = p.nodeAddr[] - else: doAssert false, $p.kind + else: + result = nil + doAssert false, $p.kind proc getNodeAddr*(a: VmArgs; i: Natural): PNode = let nodeAddr = getX(rkNodeAddr, nodeAddr) diff --git a/compiler/vmmarshal.nim b/compiler/vmmarshal.nim index b48197aefa..e1e69f6cc5 100644 --- a/compiler/vmmarshal.nim +++ b/compiler/vmmarshal.nim @@ -21,6 +21,7 @@ proc ptrToInt(x: PNode): int {.inline.} = proc getField(n: PNode; position: int): PSym = case n.kind of nkRecList: + result = nil for i in 0.. infoMax.time: infoMax = info diff --git a/lib/pure/collections/heapqueue.nim b/lib/pure/collections/heapqueue.nim index 89e532951a..bcfdf37c2b 100644 --- a/lib/pure/collections/heapqueue.nim +++ b/lib/pure/collections/heapqueue.nim @@ -59,7 +59,7 @@ proc initHeapQueue*[T](): HeapQueue[T] = ## ## **See also:** ## * `toHeapQueue proc <#toHeapQueue,openArray[T]>`_ - discard + result = default(HeapQueue[T]) proc len*[T](heap: HeapQueue[T]): int {.inline.} = ## Returns the number of elements of `heap`. diff --git a/lib/pure/collections/sequtils.nim b/lib/pure/collections/sequtils.nim index 19bc3e65c6..e2adba910e 100644 --- a/lib/pure/collections/sequtils.nim +++ b/lib/pure/collections/sequtils.nim @@ -860,7 +860,7 @@ template toSeq*(iter: untyped): untyped = inc i result else: - var result: seq[typeof(iter)]# = @[] + var result: seq[typeof(iter)] = @[] for x in iter: result.add(x) result diff --git a/lib/pure/collections/setimpl.nim b/lib/pure/collections/setimpl.nim index 7ebd227604..dbd4ce1d5e 100644 --- a/lib/pure/collections/setimpl.nim +++ b/lib/pure/collections/setimpl.nim @@ -62,6 +62,7 @@ template containsOrInclImpl() {.dirty.} = if index >= 0: result = true else: + result = false if mustRehash(s): enlarge(s) index = rawGetKnownHC(s, key, hc) diff --git a/lib/pure/collections/sets.nim b/lib/pure/collections/sets.nim index 11e3249234..7e193af1a7 100644 --- a/lib/pure/collections/sets.nim +++ b/lib/pure/collections/sets.nim @@ -128,7 +128,7 @@ proc initHashSet*[A](initialSize = defaultInitialSize): HashSet[A] = var a = initHashSet[int]() a.incl(3) assert len(a) == 1 - + result = default(HashSet[A]) result.init(initialSize) proc `[]`*[A](s: var HashSet[A], key: A): var A = diff --git a/lib/pure/collections/tableimpl.nim b/lib/pure/collections/tableimpl.nim index fa06b99234..112aaa7d06 100644 --- a/lib/pure/collections/tableimpl.nim +++ b/lib/pure/collections/tableimpl.nim @@ -56,14 +56,14 @@ template maybeRehashPutImpl(enlarge) {.dirty.} = template putImpl(enlarge) {.dirty.} = checkIfInitialized() - var hc: Hash + var hc: Hash = default(Hash) var index = rawGet(t, key, hc) if index >= 0: t.data[index].val = val else: maybeRehashPutImpl(enlarge) template mgetOrPutImpl(enlarge) {.dirty.} = checkIfInitialized() - var hc: Hash + var hc: Hash = default(Hash) var index = rawGet(t, key, hc) if index < 0: # not present: insert (flipping index) @@ -73,7 +73,7 @@ template mgetOrPutImpl(enlarge) {.dirty.} = template hasKeyOrPutImpl(enlarge) {.dirty.} = checkIfInitialized() - var hc: Hash + var hc: Hash = default(Hash) var index = rawGet(t, key, hc) if index < 0: result = false @@ -210,3 +210,5 @@ template equalsImpl(s, t: typed) = if not t.hasKey(key): return false if t.getOrDefault(key) != val: return false return true + else: + return false diff --git a/lib/pure/collections/tables.nim b/lib/pure/collections/tables.nim index 53490c911a..d4056897db 100644 --- a/lib/pure/collections/tables.nim +++ b/lib/pure/collections/tables.nim @@ -418,7 +418,7 @@ proc getOrDefault*[A, B](t: Table[A, B], key: A): B = let a = {'a': 5, 'b': 9}.toTable doAssert a.getOrDefault('a') == 5 doAssert a.getOrDefault('z') == 0 - + result = default(B) getOrDefaultImpl(t, key) proc getOrDefault*[A, B](t: Table[A, B], key: A, default: B): B = @@ -436,7 +436,7 @@ proc getOrDefault*[A, B](t: Table[A, B], key: A, default: B): B = let a = {'a': 5, 'b': 9}.toTable doAssert a.getOrDefault('a', 99) == 5 doAssert a.getOrDefault('z', 99) == 99 - + result = default(B) getOrDefaultImpl(t, key, default) proc mgetOrPut*[A, B](t: var Table[A, B], key: A, val: B): var B = @@ -1463,7 +1463,7 @@ proc getOrDefault*[A, B](t: OrderedTable[A, B], key: A): B = let a = {'a': 5, 'b': 9}.toOrderedTable doAssert a.getOrDefault('a') == 5 doAssert a.getOrDefault('z') == 0 - + result = default(B) getOrDefaultImpl(t, key) proc getOrDefault*[A, B](t: OrderedTable[A, B], key: A, default: B): B = @@ -1481,7 +1481,7 @@ proc getOrDefault*[A, B](t: OrderedTable[A, B], key: A, default: B): B = let a = {'a': 5, 'b': 9}.toOrderedTable doAssert a.getOrDefault('a', 99) == 5 doAssert a.getOrDefault('z', 99) == 99 - + result = default(B) getOrDefaultImpl(t, key, default) proc mgetOrPut*[A, B](t: var OrderedTable[A, B], key: A, val: B): var B = diff --git a/lib/std/packedsets.nim b/lib/std/packedsets.nim index 04fa78ada9..c6d007c261 100644 --- a/lib/std/packedsets.nim +++ b/lib/std/packedsets.nim @@ -198,6 +198,7 @@ proc contains*[A](s: PackedSet[A], key: A): bool = assert B notin letters if s.elems <= s.a.len: + result = false for i in 0..