Still on my journey to understand macros and the Nim AST...
Is there an easy way to get the fields of an object type at compile time in a macro? Or do I need to write another macro to walk the AST myself?
For example, given:
type Foo = object
a: int
b: string
Can I get something like:
getFields(Foo)
("a", int), ("b", string)
@SolitudeSF -- My understanding is fieldPairs only works on instances of a type, not on the`` typedesc`` itself.
fieldPairs(Foo) yields a type mismatch.
You might want something like this:
import macros
type Foo = object
a: int
b: string
macro getFields(x: typed): untyped =
let impl = getImpl(x)
let objFields = impl[2][2] # 2 is nnkObjectTy, 2 2 is nnkRecList
expectKind objFields, nnkRecList
result = nnkBracket.newTree()
for f in objFields:
expectKind f, nnkIdentDefs
result.add nnkPar.newTree(newLit f[0].strVal, newLit f[1].strVal)
for (fieldName, typeName) in getFields(Foo):
echo "Field: ", fieldName, " with type name ", typeName
It returns a bracket of (field name, type name) tuples. Both as strings, since you can't mix strings with types in a tuple. For more complicated objects you'd have to recurse on the fields with complex types of course.