Is it possible to get the fields on an object in a macro? In a 'ref object'?
I've learned a great deal about macros and AST over the course of the last two days, but this one still eludes me.
For example:
macro something(n: typed): typed =
var z: seq[string] = @[]
# stuff goes here
# ....
# ... generate some resulting methods ...
type
DirectObj = object of RootObj
abc: string
xyz: string
RefObj = ref object of RootObj
abc: string
xyz: string
RefRefObj = ref object of RefObj
def: string
something(DirectObj)
something(RefObj)
something(RefRefObj)
Given the above, how do I get z filled out with the object field names? Or is that possible?
macro something(n: typed): typed =
var z: seq[string] = @[]
let typDef = getImpl(n)
let recList = typDef[2][2]
for identDefs in recList:
for i in 0 .. identDefs.len - 3:
z.add $identDefs[i]
Works for object, needs some adjustment for ref...
Yes! That got me close enough. Thanks!
For others: the symbol needs to be looked up from the NimNode first. So the final code is:
macro something(n: typed): typed =
var z: seq[string] = @[]
let nSym = symbol(n)
let typDef = getImpl(nSym)
let recList = typDef[2][2]
for identDefs in recList:
for i in 0 .. identDefs.len - 3:
z.add $identDefs[i]
And, for a "ref object":
macro something(n: typed): typed =
var z: seq[string] = @[]
let nSym = symbol(n)
let typDef = getImpl(nSym)
let recList = typDef[2][0][2]
for identDefs in recList:
for i in 0 .. identDefs.len - 3:
z.add $identDefs[i]
Notice the extra "[0]" because a "RefTy" parents the "ObjectTy".
Just out of mild curiosity... I saw that the parent (source of Inheritance) was under typDef, so one can query that object also:
# query parent of n
let parent = typDef[2][0][1][0]
let parentSymbol = symbol(parent)
let parentTypDef = getImpl(parentSymbol)
echo parentTypDef.treeRepr
And travel further down the rabbit hole.
It is:
Nim Compiler Version 0.18.0 [Linux: amd64]
I did not compile it. It is the one in general release from the "choosenim" script.