-
Notifications
You must be signed in to change notification settings - Fork 1
/
function_macro.nim
50 lines (39 loc) · 1.23 KB
/
function_macro.nim
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
45
46
47
48
49
50
## This macro is additional modification from my thread asking on how
## to expand the defined Proc Type
## I modified and improve the answer from @mratsim here
## https://forum.nim-lang.org/t/4012#24965
## and now able to support exported procs definition
import macros
macro function_impl(head: untyped, handlertype: typed, body: untyped):
untyped =
var
handlerimpl = handlertype.symbol().getImpl()
thefunc = newNimNode nnkProcDef
params = newSeq[NimNode]()
for node in handlerimpl[2][0]:
params.add node
result = newProc(name = head,
params = params,
body = body)
var pragma = handlerimpl[2][1]
if pragma.kind != nnkEmpty:
result.pragma = pragma
macro function*(head_oftype, body: untyped): untyped =
head_oftype.expectKind nnkInfix
echo "head_oftype: ", head_oftype.repr
echo "head_len: ", head_oftype.len
var head, oftype: NimNode
case $head_oftype[0]
of "*":
head = head_oftype[1].postfix "*"
oftype = head_oftype[2].basename
of "of":
head = head_oftype[1]
oftype = head_oftype[2]
result = quote do: function_impl(`head`, `oftype`, `body`)
when isMainModule:
type
Handler = proc(x: int): int
function handleThis* of Handler:
x * 10
echo handleThis(5)