Skip to content

Commit 9c17a32

Browse files
authored
fix #19266; allow reassign discriminant field (#19567)
* add inUncheckedAssignSection * add one more test
1 parent ef3f343 commit 9c17a32

File tree

4 files changed

+39
-2
lines changed

4 files changed

+39
-2
lines changed

compiler/ccgexprs.nim

+15-1
Original file line numberDiff line numberDiff line change
@@ -2932,7 +2932,21 @@ proc expr(p: BProc, n: PNode, d: var TLoc) =
29322932
nkFromStmt, nkTemplateDef, nkMacroDef, nkStaticStmt:
29332933
discard
29342934
of nkPragma: genPragma(p, n)
2935-
of nkPragmaBlock: expr(p, n.lastSon, d)
2935+
of nkPragmaBlock:
2936+
var inUncheckedAssignSection = 0
2937+
let pragmaList = n[0]
2938+
for pi in pragmaList:
2939+
if whichPragma(pi) == wCast:
2940+
case whichPragma(pi[1])
2941+
of wUncheckedAssign:
2942+
inUncheckedAssignSection = 1
2943+
else:
2944+
discard
2945+
2946+
inc p.inUncheckedAssignSection, inUncheckedAssignSection
2947+
expr(p, n.lastSon, d)
2948+
dec p.inUncheckedAssignSection, inUncheckedAssignSection
2949+
29362950
of nkProcDef, nkFuncDef, nkMethodDef, nkConverterDef:
29372951
if n[genericParamsPos].kind == nkEmpty:
29382952
var prc = n[namePos].sym

compiler/ccgstmts.nim

+1-1
Original file line numberDiff line numberDiff line change
@@ -1566,7 +1566,7 @@ proc asgnFieldDiscriminant(p: BProc, e: PNode) =
15661566
initLocExpr(p, e[0], a)
15671567
getTemp(p, a.t, tmp)
15681568
expr(p, e[1], tmp)
1569-
if optTinyRtti notin p.config.globalOptions:
1569+
if optTinyRtti notin p.config.globalOptions and p.inUncheckedAssignSection == 0:
15701570
let field = dotExpr[1].sym
15711571
genDiscriminantCheck(p, a, tmp, dotExpr[0].typ, field)
15721572
message(p.config, e.info, warnCaseTransition)

compiler/cgendata.nim

+1
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,7 @@ type
9999
withinTryWithExcept*: int # required for goto based exception handling
100100
withinBlockLeaveActions*: int # complex to explain
101101
sigConflicts*: CountTable[string]
102+
inUncheckedAssignSection*: int
102103

103104
TTypeSeq* = seq[PType]
104105
TypeCache* = Table[SigHash, Rope]

tests/objvariant/treassign.nim

+22
Original file line numberDiff line numberDiff line change
@@ -34,3 +34,25 @@ proc passToVar(x: var Token) = discard
3434
t.curr = TokenObject(kind: t.curr.kind, foo: "abc")
3535

3636
t.curr.kind = Token.foo
37+
38+
39+
block:
40+
type
41+
TokenKind = enum
42+
strLit, intLit
43+
Token = object
44+
case kind*: TokenKind
45+
of strLit:
46+
s*: string
47+
of intLit:
48+
i*: int64
49+
50+
var t = Token(kind: strLit, s: "abc")
51+
52+
{.cast(uncheckedAssign).}:
53+
54+
# inside the 'cast' section it is allowed to assign to the 't.kind' field directly:
55+
t.kind = intLit
56+
57+
{.cast(uncheckedAssign).}:
58+
t.kind = strLit

0 commit comments

Comments
 (0)