File: importutils.nim

package info (click to toggle)
nim 2.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,911,644 kB
  • sloc: sh: 24,603; ansic: 1,761; python: 1,492; makefile: 1,013; sql: 298; asm: 141; xml: 13
file content (44 lines) | stat: -rw-r--r-- 1,293 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
##[
Utilities related to import and symbol resolution.

Experimental API, subject to change.
]##

#[
Possible future APIs:
* module symbols (https://github.com/nim-lang/Nim/pull/9560)
* whichModule (subsumes canImport / moduleExists) (https://github.com/timotheecour/Nim/issues/376)
* getCurrentPkgDir (https://github.com/nim-lang/Nim/pull/10530)
* import from a computed string + related APIs (https://github.com/nim-lang/Nim/pull/10527)
]#

when defined(nimImportutilsExample):
  type
    Foo = object
      f0: int # private
    Goo*[T] = object
      g0: int # private
  proc initFoo*(): auto = Foo()

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
    #     f0: int # private
    #   Goo*[T] = object
    #     g0: int # private
    # proc initFoo*(): auto = Foo()
    var f = initFoo()
    block:
      assert not compiles(f.f0)
      privateAccess(f.type)
      f.f0 = 1 # accessible in this scope
      block:
        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