summary refs log tree commit diff stats
diff options
context:
space:
mode:
authorAdam Strzelecki <ono@java.pl>2015-05-13 22:32:10 +0200
committerAdam Strzelecki <ono@java.pl>2015-05-17 15:28:41 +0200
commit1d47617d1b72c642fac5543f38aa24330b0f9a19 (patch)
treede71d33b3adcc3264dcd5a84ff0b0ed35fc40cc6
parent63f1e0327817b0e7abacc3c0214ea94980f5c2ea (diff)
downloadNim-1d47617d1b72c642fac5543f38aa24330b0f9a19.tar.gz
Macros: Introduce getType(t: typedesc): NimNode
Since typedesc are exception in macros and they are not implicitly converted to
NimNode on macro call, we need some means to perform such conversion on demand.

Fortunately it is as simple as declaring new magic "NGetType" proc with
typedesc parameter.

NOTE: Keeping actual macro exceptional behavior for typedesc is important,
since it allows passing typedesc macro parameter to other procs or macros
expecting type parameter. If typedesc parameter was implicitly converted, then
we would lost this ability.
-rw-r--r--lib/core/macros.nim6
-rw-r--r--tests/macros/tgettype.nim20
2 files changed, 26 insertions, 0 deletions
diff --git a/lib/core/macros.nim b/lib/core/macros.nim
index 35f0f61c1..7e6e4ccc9 100644
--- a/lib/core/macros.nim
+++ b/lib/core/macros.nim
@@ -177,6 +177,12 @@ proc getType*(n: NimNode): NimNode {.magic: "NGetType", noSideEffect.}
   ## resolve recursive types, you have to call 'getType' again. To see what
   ## kind of type it is, call `typeKind` on getType's result.
 
+proc getType*(n: typedesc): NimNode {.magic: "NGetType", noSideEffect.}
+  ## Returns the Nim type node for given type. This can be used to turn macro
+  ## typedesc parameter into proper NimNode representing type, since typedesc
+  ## are an exception in macro calls - they are not mapped implicitly to
+  ## NimNode like any other arguments.
+
 proc typeKind*(n: NimNode): NimTypeKind {.magic: "NGetType", noSideEffect.}
   ## Returns the type kind of the node 'n' that should represent a type, that
   ## means the node should have been obtained via `getType`.
diff --git a/tests/macros/tgettype.nim b/tests/macros/tgettype.nim
new file mode 100644
index 000000000..0eab6c0a0
--- /dev/null
+++ b/tests/macros/tgettype.nim
@@ -0,0 +1,20 @@
+discard """
+msg: '''ObjectTy(Sym(Model), RecList(Sym(name), Sym(password)))
+BracketExpr(Sym(typeDesc), Sym(User))'''
+"""
+import strutils, macros
+
+type
+  Model = object of RootObj
+  User = object of Model
+    name : string
+    password : string
+
+macro testUser: expr =
+  return newLit(User.getType.lispRepr)
+
+macro testGeneric(T: typedesc[Model]): expr =
+  return newLit(T.getType.lispRepr)
+
+echo testUser
+echo User.testGeneric