To start with a practical example, I would like to talk about, how I would pattern match the NimNode types, mostly because they are types I would care about. The syntax should be almost identical to the construction, just it should work in reverse. Here is an example of how I could imagine it: import macros proc foobar(arg: NimNode, id: int): void = echo arg.repr macro myMacro(arg:untyped): untyped = for section in arg: case section # pattern matching is always the whole object, not just the kind of nnkCall.newTree(ident"variantA", `stmtList`): foobar(stmtList, 0) of nnkCall.newTree(ident"variontB", `stmtList`): foobar(stmtList, 1) of nnkCall.newTree(ident"variantC", nnkStmtList.newTree(nnkCall.newTree(ident"subVariantA", `stmtList`))): foobar(stmtList, 2) of nnkCall.newTree(ident"variantC", nnkStmtList.newTree(nnkCall.newTree(ident"subVariantB", `stmtList`))): foobar(stmtList, 3) Mymacro: variantA: a += 1 b += 2 variantB: a += 4 b += 8 variantC: subVariantA: a += 8 b += 19 variantC: subVariantB: a += 20 b += 30
Full input ast: StmtList Call Ident !"variantA" StmtList Infix Ident !"+=" Ident !"a" IntLit 1 Infix Ident !"+=" Ident !"b" IntLit 2 Call Ident !"variantB" StmtList Infix Ident !"+=" Ident !"a" IntLit 4 Infix Ident !"+=" Ident !"b" IntLit 8 Call Ident !"variantC" StmtList Call Ident !"subVariantA" StmtList Infix Ident !"+=" Ident !"a" IntLit 8 Infix Ident !"+=" Ident !"b" IntLit 19 Call Ident !"variantC" StmtList Call Ident !"subVariantB" StmtList Infix Ident !"+=" Ident !"a" IntLit 20 Infix Ident !"+=" Ident !"b" IntLit 30 I have to admit thet `newTree` is not the best name to extract trees, but that is the way I construct them, and that is the only syntax that works reliably with every node kind.