Skip to content

Commit

Permalink
fix jsonutils macro with generic case object (#24429)
Browse files Browse the repository at this point in the history
split from #24425

The added test did not work previously. The result of `getTypeImpl` is
the uninstantiated AST of the original type symbol, and the macro
attempts to use this type for the result. To fix the issue, the provided
`typedesc` argument is used instead.
  • Loading branch information
metagn authored Nov 12, 2024
1 parent 76c5f16 commit 45e21ce
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/std/jsonutils.nim
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ macro initCaseObject(T: typedesc, fun: untyped): untyped =
else: raiseAssert $t.kind # xxx `nnkPtrTy` could be handled too
doAssert t2.kind == nnkRecList
result = newTree(nnkObjConstr)
result.add sym
result.add T
for ti in t2:
if ti.kind == nnkRecCase:
let key = ti[0][0]
Expand Down
13 changes: 13 additions & 0 deletions tests/stdlib/tjsonutils.nim
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,19 @@ template fn() =
# sanity check: nesting inside a tuple
testRoundtrip((Foo[int](x0: 1.5, t1: false, z2: 6), "foo")): """[{"x0":1.5,"t1":false,"z2":6,"x1":""},"foo"]"""

block: # generic case object using generic type
type Foo[T] = ref object
x0: float
case t1: bool
of true: z1: int8
of false: z2: uint16
x1: string
x2: T
testRoundtrip(Foo[float](t1: true, z1: 5, x1: "bar", x2: 2.5)): """{"x0":0.0,"t1":true,"z1":5,"x1":"bar","x2":2.5}"""
testRoundtrip(Foo[int](x0: 1.5, t1: false, z2: 6, x2: 2)): """{"x0":1.5,"t1":false,"z2":6,"x1":"","x2":2}"""
# sanity check: nesting inside a tuple
testRoundtrip((Foo[int](x0: 1.5, t1: false, z2: 6, x2: 2), "foo")): """[{"x0":1.5,"t1":false,"z2":6,"x1":"","x2":2},"foo"]"""

block: # case object: 2 discriminants, `when` branch, range discriminant
type Foo[T] = object
case t1: bool
Expand Down

0 comments on commit 45e21ce

Please sign in to comment.