make privateAccess work with generic types and generic instantiations; fix a SIGSEGV (#18260)

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
This commit is contained in:
Timothee Cour
2021-06-19 11:24:46 -07:00
committed by GitHub
parent 5d15bd7b61
commit 7714ab468a
5 changed files with 118 additions and 15 deletions

View File

@@ -13,22 +13,32 @@ Possible future APIs:
]#
when defined(nimImportutilsExample):
type Foo = object
x1: int # private
type
Foo = object
f0: int # private
Goo*[T] = object
g0: int # private
proc initFoo*(): auto = Foo()
proc privateAccess*(t: typedesc[object|(ref object)|(ptr object)]) {.magic: "PrivateAccess".} =
proc privateAccess*(t: typedesc) {.magic: "PrivateAccess".} =
## Enables access to private fields of `t` in current scope.
runnableExamples("-d:nimImportutilsExample"):
# here we're importing a module containing:
# type Foo = object
# x1: int # private
# type
# Foo = object
# f0: int # private
# Goo*[T] = object
# g0: int # private
# proc initFoo*(): auto = Foo()
var a = initFoo()
var f = initFoo()
block:
assert not compiles(a.x1)
privateAccess(a.type)
a.x1 = 1 # accessible in this scope
assert not compiles(f.f0)
privateAccess(f.type)
f.f0 = 1 # accessible in this scope
block:
assert a.x1 == 1 # still in scope
assert not compiles(a.x1)
assert f.f0 == 1 # still in scope
assert not compiles(f.f0)
# this also works with generics
privateAccess(Goo)
assert Goo[float](g0: 1).g0 == 1