I am going through examples of basic metaprogramming challenges, as proposed to me by the ChatGPT4 bot: https://chat.openai.com/share/9056f7cb-e20f-41ec-8a2f-c6b8ea0ba484
One of these is type introspection: Given a Nim object or type, explore and print its fields using Nim's metaprogramming capabilities.
Let's say I have an object defined with:
type
Person = object
name: string
age: int
Can I list the attributes and the types associated to each attributes given:
If so, how?
Notice that answer to 1) is yes and is pretty easy, but I am not sure how to do it in the most generic way (supporting inheritance, pragmas, generics, object variants and so on …). How could I use getType, getImpl or getTypeImpl ?
I know my question is a bit vague and theoretical. I do not have a project with a purpose in mind, I just want a more in depth tutorial to metaprogramming than the one given on the website. So I can't answer questions of the type: "Do you need to list attributes and their types at compile-time or runtime". My answer would probably be both.
I don't mind
Not that it's well documented, but a ton of type operations are defined inside https://github.com/beef331/micros/blob/master/src/micros/definitions/objectdefs.nim . Most important to this question would be https://github.com/beef331/micros/blob/master/src/micros/definitions/objectdefs.nim#L229-L241
Another way of doing type introspection is just using the fieldPairs/fields iterator, you can use this in a variety of ways, the simplest is as follows.
proc listStuffs(obj: object) =
for name, field in obj.fieldPairs:
echo name, ": ", field
proc listStuffs(t: typedesc[object]) = listStuffs(default(t))