From 39f925b95d57a429a808cfa1b96d6fae12a72dbf Mon Sep 17 00:00:00 2001 From: ringabout <43030857+ringabout@users.noreply.github.com> Date: Tue, 1 Nov 2022 01:42:45 +0800 Subject: [PATCH] fixes #20715; range[a..b] inside object variant fails (#20716) * fixes #20715; range[a..b] inside object variant fails * step one fix * better fix * fixes private fields * mistake --- compiler/sem.nim | 11 ++++----- tests/objects/tobject_default_value.nim | 30 +++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 5 deletions(-) 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()