diff options
author | zah <zahary@gmail.com> | 2019-09-30 23:24:57 +0300 |
---|---|---|
committer | Andreas Rumpf <rumpf_a@web.de> | 2019-09-30 22:24:57 +0200 |
commit | a4ade435365065b7722d8111e0ad298f4f766452 (patch) | |
tree | 4447564a1af973837ca337bd7a0833c07d93135d | |
parent | dd082b6ec8308034a48761bf8a441b119ec0f351 (diff) | |
download | Nim-a4ade435365065b7722d8111e0ad298f4f766452.tar.gz |
macros.newLit now works for ref object types (#12307)
-rw-r--r-- | changelog.md | 2 | ||||
-rw-r--r-- | lib/core/macros.nim | 6 | ||||
-rw-r--r-- | tests/macros/tnewlit.nim | 25 |
3 files changed, 33 insertions, 0 deletions
diff --git a/changelog.md b/changelog.md index 85e381342..32c6935db 100644 --- a/changelog.md +++ b/changelog.md @@ -17,6 +17,7 @@ ## Library additions +- `macros.newLit` now works for ref object types. ## Library changes @@ -41,3 +42,4 @@ ## Bugfixes + diff --git a/lib/core/macros.nim b/lib/core/macros.nim index 408cbb9d6..f4653ca1f 100644 --- a/lib/core/macros.nim +++ b/lib/core/macros.nim @@ -742,6 +742,12 @@ proc newLit*(arg: object): NimNode {.compileTime.} = for a, b in arg.fieldPairs: result.add nnkExprColonExpr.newTree( newIdentNode(a), newLit(b) ) +proc newLit*(arg: ref object): NimNode {.compileTime.} = + ## produces a new ref type literal node. + result = nnkObjConstr.newTree(arg.type.getTypeInst[1]) + for a, b in fieldPairs(arg[]): + result.add nnkExprColonExpr.newTree(newIdentNode(a), newLit(b)) + proc newLit*[N,T](arg: array[N,T]): NimNode {.compileTime.} = result = nnkBracket.newTree for x in arg: diff --git a/tests/macros/tnewlit.nim b/tests/macros/tnewlit.nim index 194f035ba..70683f880 100644 --- a/tests/macros/tnewlit.nim +++ b/tests/macros/tnewlit.nim @@ -5,6 +5,14 @@ type a : int b : string + RefObject = ref object + x: int + + RegularObject = object + x: int + + ObjectRefAlias = ref RegularObject + macro test_newLit_MyType: untyped = let mt = MyType(a: 123, b:"foobar") result = newLit(mt) @@ -167,3 +175,20 @@ macro test_newLit_set: untyped = block: let tmp: set[MyEnum] = {MyEnum.low .. MyEnum.high} doAssert tmp == test_newLit_set + +macro test_newLit_ref_object: untyped = + var x = RefObject(x: 10) + return newLit(x) + +block: + let x = test_newLit_ref_object() + doAssert $(x[]) == "(x: 10)" + +macro test_newLit_object_ref_alias: untyped = + var x = ObjectRefAlias(x: 10) + return newLit(x) + +block: + let x = test_newLit_object_ref_alias() + doAssert $(x[]) == "(x: 10)" + |