Skip to content

Instantly share code, notes, and snippets.

@diegogub
Last active April 2, 2018 13:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save diegogub/dbaa265235d8f672c3644f09b2a1c679 to your computer and use it in GitHub Desktop.
Save diegogub/dbaa265235d8f672c3644f09b2a1c679 to your computer and use it in GitHub Desktop.
import macros, json
type Event = ref object of RootObj
id: string
type TestMade = ref object of Event
name: string
type Test = ref object of Event
`result`: string
let data = parseJson("""{ "id" : "test" ,"name": "diego"}""")
macro mcase(val, prefix: static[string], events: varargs[typed]): untyped =
result = nnkStmtList.newTree()
var event_vars = nnkStmtList.newTree()
var caseNode = nnkCaseStmt.newTree()
caseNode.add(newLit(val))
for event in events:
let name = toNimIdent(prefix & "_" & $event)
event_vars.add quote do:
var `name` = `event`()
caseNode.add(
nnkOfBranch.newTree(
newLit($event),
quote do:
`name` = to(data, `event`)
)
)
result.add(event_vars)
result.add(caseNode)
mcase("TestMade", "e",
TestMade,
Test,
)
echo e_TestMade[]
echo e_Test[]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment