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:
parent
ecd3c80e7e
commit
12bac28d23
6 changed files with 119 additions and 36 deletions
39
tests/accept/compile/ttypeselectors.nim
Normal file
39
tests/accept/compile/ttypeselectors.nim
Normal 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
|
||||
|
||||
Loading…
Add table
Add a link
Reference in a new issue