Hello Everyone I am a noob in nim and I am trying to create a new type using macros. I want to create a type based on the data in a config file (which I have currently not implemented). Below is my code and it always gives me a type expected. Can some please help me. TIA
import macros
macro typeDef(): NimNode =
var parameters: seq[NimNode]
parameters = @[]
parameters.add(ident("string"))
parameters.add(newIdentDefs(ident("a"), ident("string")))
var procedure = newProc(params=parameters,body=newEmptyNode() )
var temp = newStmtList(procedure)
echo temp.repr
result = temp
when isMainModule:
type foo = typeDef()
This is the error I encounter
Hint: used config file 'C:\nim-0.16.0\config\nim.cfg' [Conf]
Hint: system [Processing]
Hint: moduleTest [Processing]
Hint: macros [Processing]
proc (a: string): string
moduleTest.nim(15, 23) Error: type expected
this does not solve your problem, but by executing it, you should be able to see what you did wrong:
import macros
type
bar = proc(a: string): string
dumpTree:
type
bar = proc(a: string): string
macro typeDef(): untyped =
var parameters: seq[NimNode]
parameters = @[]
parameters.add(ident("string"))
parameters.add(newIdentDefs(ident("a"), ident("string")))
var procedure = newProc(params=parameters,body=newEmptyNode() )
var temp = newStmtList(procedure)
echo temp.treeRepr
result = temp
when isMainModule:
type foo = typeDef()
And the result of your macro should be untyped as in untyped syntax tree. NimNode is never the result type of a macro.
newProc returns a NimNode with kind == nnkProcDef. However, you need a nnkProcTy. So you have to put it together yourself, since newProc does not accept nnkProcTy as procType (don't ask me why).
Have a look at
import macros
dumpTree:
type foo = proc(a: string): string
it will show you what you will need to put together.