diff --git a/compiler/sem.nim b/compiler/sem.nim index 8f766f126c8e..3c8ced6b8418 100644 --- a/compiler/sem.nim +++ b/compiler/sem.nim @@ -599,15 +599,16 @@ proc defaultFieldsForTheUninitialized(c: PContext, recNode: PNode): seq[PNode] = of nkRecCase: let discriminator = recNode[0] var selectedBranch: int - let defaultValue = discriminator.sym.ast + var defaultValue = discriminator.sym.ast if defaultValue == nil: # None of the branches were explicitly selected by the user and no value # was given to the discrimator. We can assume that it will be initialized # to zero and this will select a particular branch as a result: - selectedBranch = recNode.pickCaseBranchIndex newIntNode(nkIntLit#[c.graph]#, 0) - else: # Try to use default value - selectedBranch = recNode.pickCaseBranchIndex defaultValue - result.add newTree(nkExprColonExpr, discriminator, defaultValue) + defaultValue = newIntNode(nkIntLit#[c.graph]#, 0) + defaultValue.typ = discriminator.typ + selectedBranch = recNode.pickCaseBranchIndex defaultValue + defaultValue.flags.incl nfUseDefaultField + result.add newTree(nkExprColonExpr, discriminator, defaultValue) result.add defaultFieldsForTheUninitialized(c, recNode[selectedBranch][^1]) of nkSym: let field = recNode.sym diff --git a/tests/objects/tobject_default_value.nim b/tests/objects/tobject_default_value.nim index 643bba832cb1..975a1e14614a 100644 --- a/tests/objects/tobject_default_value.nim +++ b/tests/objects/tobject_default_value.nim @@ -426,6 +426,36 @@ template main {.dirty.} = let x = default(A) doAssert $x == "(d: Uninitialized DateTime)" + block: # bug #20715 + block: + type + Foo = enum + A + B + + Bar = object + case foo: Foo + of A: + t: range[-1..2] + else: discard + + var d = default(Bar) + doAssert d.t == -1 + + block: + type + Foo = enum + A + B + + Bar = object + case foo: Foo + of A: + t: range[0..2] + else: discard + + var d = default(Bar) + doAssert d.t == 0 static: main() main()