macros and templates can be expanded anywhere where a type is expected.

This allows for various type selection algorithms to be implemented.
See tests / accept / compile / ttypeselectors.nim for examples.
This commit is contained in:
Zahary Karadjov 2011-11-16 02:18:10 +02:00
commit 12bac28d23
6 changed files with 119 additions and 36 deletions

View file

@ -0,0 +1,39 @@
import macros
template selectType(x: int): typeDesc =
when x < 10:
int
else:
string
template simpleTypeTempl: typeDesc =
string
macro typeFromMacro(s: expr): typeDesc =
result = newNimNode(nnkIdent)
result.ident = !"string"
# result = newIdentNode"string"
proc t1*(x: int): simpleTypeTempl() =
result = "test"
proc t2*(x: int): selectType(100) =
result = "test"
proc t3*(x: int): selectType(1) =
result = 10
proc t4*(x: int): typeFromMacro() =
result = "test"
var x*: selectType(50) = "test"
proc t5*(x: selectType(5)) =
var y = x + 10
echo y
var y*: type(t2(100)) = "test"
proc t6*(x: type(t3(0))): type(t1(0)) =
result = $x