I am trying learn more about how Nim macros work and get used to them.
In this case, I want to pass an object type as an argument to a macro, which then inspects the provided object type and gets all fields (only var or let sections are expected) as NimNode`s. Then, I want to do further operations with those fields, like e.g. instantiating the provided `object, filling its fields with information provided from a different source. (Similar to a macro mapping fields from a configuration file to an object type, except the provided type is also variable and should be dynamically processed.)
How can I inspect the object type's fields?
There's probably a neater way to do it but this works:
import macros
macro printFields(obj: typedesc) =
for field in getType(obj)[1].getTypeImpl[2]:
let
name = field[0].strVal
fieldType = field[1].strVal
echo "name: ", name
echo "type: ", fieldType
echo "------"
type
MyObj = object
stringField: string
power: int
printFields MyObj
name: stringField
type: string
------
name: power
type: int
------
@geotre
Wow, thank you so much, this helped really A LOT!
For future readers, my macro expects a
type
MyObj = ref object of myObj
stringField: string
power: int
So here is the spec for retrieving the RecList from a ref object:
for field in model.getType[1][1].getTypeImpl[2]:
# For `ref object of myObj`.
let
name = field[0].strVal
fieldType = field[1].strVal
echo "loop"
echo "name: ", name
echo "type: ", fieldType
echo "------"
Thank you!