Hi,
i'll try to explain my problem with an example
import json
import macros
type
Handler = proc(event: any): any # this type must remain "generic" (not sure if any is the most appropriate)
MyEvent = tuple # the name and the fields of the tuple can change
name: string
age: int
proc handler(event: MyEvent): MyEvent = # this must be specific with the tuple
echo event
event
macro myMacro(handler: any): typedesc
# obtain type MyEvent from handler
# maybe macro is not the most appropriate way...
# any suggestion, please?
proc start*(handler: Handler) =
let eventJson = parseJson("""{ "name": "Nim", "age": 12 }""")
let eventType = myMacro(handler)
var event = to(eventJson, eventType)
let response = handler(event)
when isMainModule:
start(handler)
My goal is to "obtain" dynamically at compile time the type of the tuple used in the handler proc, in order to perform the appropriate json unmarshal via to() function.
I thought that a macro can be useful, but I don't know how to implement it... Can anyone provide some suggestion, please?
I am not sure that "macro" is the most appropriate way of acheiving my goal, so feel free to propose other implementations
Thanks in advance Gianni
Hi inventormatt, your macro works like a charm! Thank you.
About the handler type, my goal is to say: "a procedure (with one parameter that is a tuple) returning a tuple"
type
Handler = proc(event: tuple): tuple
yes I found a way to do it https://play.nim-lang.org/#ix=2HcA.
type
Handler[T:tuple] = proc(event:tuple): tuple